<?php

namespace Admin\Frontend\Controllers;

use Admin\Models\stats\XhstatsStud;
use Admin\Models\stats\XhstatsTaskuser;
use Admin\Models\stats\XhstatsTch;
use Admin\Models\user\XhsysUser;
use Helpers\Cache;
use Modules\School;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Helpers\Tool;
use Helpers\Main;
use Helpers\UserPower;
use Helpers\HttpClient;
use Helpers\Assets;
use Helpers\Template;
use Admin\Models\sys\XhsysConfig;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\school\XhschoolInfo;
use Phalcon\Db\Column;
use Phalcon\Di\Service;

class StatsController extends ControllerBase
{

    private $userTaskEnum = [
//        'iStatus'   => [
//            0   => '正在执行中...',
//            1   => '已完成',
//            2   => '完成但有错误',
//            3   => '用户数据统计缺失'
//        ],
        'iUserType' => [
            1   => '学生',
            4   => '教师'
        ]
    ];
    private $schoolAppEnum = [
        'userType' => [1 => '学生', 2 => '教师', 3 => '家长', 4 => '通用']
    ];

    /**
     * 根据应用编号返回统计数据库连接
     *
     * @param $appCode
     * @return bool|Mysql
     *
     * create by ck 20170522
     */
    private function connStatsDatabase($appCode)
    {
        $statsConfig = Main::getConfigByName('stats_' . $appCode);
        if(!$statsConfig) return false;
        $statsConfig = explode('|', $statsConfig['readDB']);
        return new Mysql([
            'host'      => $statsConfig[0],
            'username'  => $statsConfig[1],
            'password'  => $statsConfig[2],
            'dbname'    => $statsConfig[3],
            'charset'   => $statsConfig[4]
        ]);
    }

    /**
     * 获取统计应用列表
     *
     * @return array    --编号=>名称
     *
     * create by ck 20170506
     */
    private function getStatsAppInfo()
    {
        if(Cache::exists('stats_app_list')){
            return Cache::get('stats_app_list');
        }
        $statAppList = [];
        $appStatsList = XhsysConfig::find([
            'columns'    => 'sConfigName,sConfigExplain',
            'conditions' => 'bDelete = 0 AND sSortName = "stats" AND sConfigName like "stats\_%"'
        ])->toArray();
        foreach($appStatsList as $key => $value){
            $statAppList[end(explode('_', $value['sConfigName']))] = end(explode('_', $value['sConfigExplain']));
        }
        Cache::save('stats_app_list', $statAppList);
        return $statAppList;
    }

    /**
     * 根据应用编号获取需要统计的项目
     *
     * @param $appCode
     * @return array
     *
     * create by ck 20170525
     */
    private function getNeedStatsItem($appCode)
    {
        $statsInfo  = Main::getConfigByName('statsInfo');
        $statsItem  = [];
        foreach($statsInfo as $key => $info){
            if(!strrchr($key, 'App')) continue;
            $info = explode(',', $info);
            in_array($appCode, $info) and $statsItem[] = substr($key, 0, strrpos($key,'App'));
        }
        return $statsItem;
    }

    /**
     * 主页
     *
     * create by ck 20161108
     * modify by ck 20170104    更改数据来源
     * modify by ck 20170413    应用更改为配置文件
     * modify by ck 20170506    添加学校情况图表
     * modify by ck 20170523    应用清空根据cookie自动选中
     */
    public function indexAction()
    {
        $this->view->pick('stats/index');
        Main::showNavPosition();
        Assets::xhChart('js/stats/index.js');
        if (!UserPower::checkUserPower('Stats_App')) {
            return $this->sendViewError('无查看权限');
        }
        $viewVar = ['appStatsList' => $this->getStatsAppInfo()];

        //如有学校查看权限则展示图表
        $schoolPowerId = School::getPower();
        if ($schoolPowerId) {
            $schoolChartInfo = [];
            $schoolChartDefault = $this->getSchoolChartInfo();
            foreach ($schoolChartDefault as $info) {
                if (UserPower::checkUserPower($info['power'])) {
                    $schoolChartInfo[] = ['title' => $info['title'], 'url' => $info['url']];
                }
            }
            $viewVar['schoolChartInfo'] = $schoolChartInfo;
        }

        if (UserPower::checkUserPower('Stats_App_LoginChart')) {
            $viewVar['allLoginChart'] = true;
        }

        //查看应用版本使用情况
        if (UserPower::checkUserPower('Stats_App_AppChart')) {
            $viewVar['allowAppChart'] = true;
            $statsInfo = Main::getConfigByName('statsInfo');

            //获取2.0需要统计应用
            $schoolAppList2 = [];
            $appList = explode(',', $statsInfo['appName']);
            if($this->cookies->has('schoolAppVer2_' . Main::getLoginUserInfo('userId'))){
                $cookieAppName = $this->cookies->get('schoolAppVer2_' . Main::getLoginUserInfo('userId'))->getValue();
                $cookieAppName = explode(',', base64_decode($cookieAppName));
                foreach($appList as $appName){
                    $schoolAppList2[] = ['name' => $appName, 'checked' => in_array($appName, $cookieAppName)];
                }
            }
            else{
                foreach($appList as $appName){
                    $schoolAppList2[] = ['name' => $appName, 'checked' => true];
                }
            }
            $viewVar['schoolAppList2'] = $schoolAppList2;

            //获取3.0需要统计应用
            $schoolAppList3 = [];
            $httpClient = new HttpClient(Main::getConfigByName('jAppServer')['url']);
            $response = $httpClient->postJson('/api/v1/apps/assigned', ['packageNames' => $statsInfo['ridPackage'] ?: '']);
            if ($response->isSuccess()) {
                $schoolAppList3 = $response->toArray();
                $cookieAppPackage = [];
                if($this->cookies->has('schoolAppVer3_' . Main::getLoginUserInfo('userId'))){
                    $cookieAppPackage = $this->cookies->get('schoolAppVer3_' . Main::getLoginUserInfo('userId'))->getValue();
                    $cookieAppPackage = explode(',', base64_decode($cookieAppPackage));
                }
                //添加用户类型及默认选中
                foreach ($schoolAppList3 as $index => $app) {
                    $schoolAppList3[$index]['appName'] .= '-' . $this->schoolAppEnum['userType'][$app['userType']];
                    $schoolAppList3[$index]['checked'] = $cookieAppPackage ? in_array($app['packageName'], $cookieAppPackage) : true;
                }
            }
            $viewVar['schoolAppList3'] = $schoolAppList3;
        }
        return $this->view->setVars($viewVar);
    }

    /**
     * 获取学校图表配置信息（命名/权限）
     *
     * @param $target
     * @param null $type
     * @return array|bool
     *
     * create by ck 20170506
     */
    private function getSchoolChartInfo($target = null, $type = null)
    {
        $info = [
            'fix'       => [
                'name'  => '布置次数',
                'title' => '布置情况',
                'field' => 'iTaskFixNum',
                'url'   => $this->url->get('Stats/schoolChart/fix'),
                'power' => 'Stats_App_FixChart'
            ],
            'brush'      => [
                'name'  => '刷题量',
                'title' => '刷题情况',
                'field' => 'iSumNum',
                'url'   => $this->url->get('Stats/schoolChart/brush'),
                'power' => 'Stats_App_TaskChart'
            ],
            'practice'  => [
                'name'  => '自练篇数',
                'title' => '自练情况',
                'field' => 'iPracticeNum',
                'url'   => $this->url->get('Stats/schoolChart/practice'),
                'power' => 'Stats_App_PracticeChart'
            ],
            'read'      => [
                'name'  => '阅读篇数',
                'title' => '阅读情况',
                'field' => 'iPracticeNum',
                'url'   => $this->url->get('Stats/schoolChart/read'),
                'power' => 'Stats_App_ReadChart'
            ],
            'duration'    => [
                'name'  => '时长（分）',
                'title' => '时长情况',
                'field' => 'FORMAT(iTaskTimeCost/60,0)',
                'url'   => $this->url->get('Stats/schoolChart/duration'),
                'power' => 'Stats_App_DurationChart'
            ]
        ];
        if(!$target) return $info;
        if(!isset($info[$target])) return false;
        if($type == 'power'){
            return UserPower::checkUserPower($info[$target][$type]);
        }
        return $type ? $info[$target][$type] : $info[$target];
    }

    /**
     * 学校图表界面（根据target区分）
     *
     * @param string $target
     * @param bool $more
     * @return bool
     *
     * create by ck 20170506
     */
    public function schoolChartAction($target = '', $more = true)
    {
        if(!$this->getSchoolChartInfo($target)){
           $this->dispatcher->forward([
                'controller'    => 'index',
                'action'        => 'show404'
            ]);
            return false;
        }

        $this->view->pick('stats/schoolChart');
        Assets::xhChart('js/stats/schoolChart.js');
        $schoolPowerId = School::getPower();
        $schoolPowerId or die(Main::showMessageModal('对不起，您没有查看此页面的权限！'));
        $this->getSchoolChartInfo($target, 'power') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！'));

        //展示搜索条件
        if($more === true){
            $this->view->setTemplateBefore('schoolChart');
            Assets::select2();
            Main::showNavPosition('应用统计', '布置情况');

            //获取默认时间
            $config = Main::getConfigByName('statsInfo');
            $chartDays = $config['chartDays'] ? $config['chartDays'] : 30;
            $endDate = date('Y-m-d', time() - 24*3600);
            $startDate = date('Y-m-d', strtotime($endDate . "-{$chartDays} days"));

            //处理有权限学校
            if($schoolPowerId === true){
                $schoolPowerId = XhschoolInfo::getSchoolSupportArray();
                unset($schoolPowerId[900090009]);
            }

            $this->view->setVars([
                'schoolArr' => $schoolPowerId,
                'startDate' => $startDate,
                'endDate'   => $endDate
            ]);
        }
        return true;
    }

    /**
     * 获取学校图表数据（根据target区分）
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170506
     */
    public function getSchoolChartAction()
    {
        $target     = $this->request->getPost('target', 'string');
        $schoolId   = $this->request->getPost('schoolId', 'int');
        $startDate  = $this->request->getPost('startDate', 'string');
        $endDate    = $this->request->getPost('endDate', 'string');

        $targetInfo = $this->getSchoolChartInfo($target) or die('无目标类型');

        //获取配置/统计应用等信息
        $config = Main::getConfigByName('statsInfo');
        $targetAppList = explode(',', $config[$target . 'App']);
        $statsAppList = $this->getStatsAppInfo();
        $data = [
            'series' => [['name' => $targetInfo['name'], 'source' => 'num']],
            'xList'  => []
        ];

        //处理学校权限条件
        $schoolCondition = '';
        if($schoolId){
            $schoolPowerId = $schoolId;
            $schoolCondition = " AND iSchoolId = {$schoolPowerId}";
        }
        else{
            $schoolPowerId = School::getPower();
            if(!$schoolPowerId) die(json_encode($data));
            if($schoolPowerId !== true) {
                $schoolPowerId = implode(',', $schoolPowerId);
                $schoolCondition = " AND iSchoolId IN ({$schoolPowerId})";
            }
        }

        //未指定时间则读取默认时间段
        if(!$startDate && !$endDate) {
            $chartDays = $config['chartDays'] ? $config['chartDays'] : 30;
            $endDate = date('Y-m-d', time() - 24 * 3600);
            $startDate = date('Y-m-d', strtotime($endDate . "-{$chartDays} days"));
        }

        //统计每个应用布置数量
        foreach($targetAppList as $appCode){
            if(!array_key_exists($appCode, $statsAppList)) continue;
            $data['xList'][] = $statsAppList[$appCode];

            if(APP_DEV){
                $data['num'][] = rand(0, 10000);
                continue;
            }
            $conn = $this->connStatsDatabase($appCode);
            $conn or die;
            $sql = "SELECT SUM({$targetInfo['field']}) as count FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startDate}' AND tTargetDate <= '{$endDate}'{$schoolCondition}";
            $result = $conn->fetchOne($sql);
            $data['num'][] = $result['count'];
        }
        return $this->response->setJsonContent($data);
    }

    /**
     * 根据学校ID，应用名称获取老师布置次数情况
     *
     * create by ck 20170531
     */
    public function schoolSingleFixInfoAction()
    {
        $this->view->pick('stats/schoolSingleFixInfo');
        $schoolId   = $this->request->getQuery('schoolId', 'int');
        $appName    = $this->request->getQuery('appName', 'string');
        $startDate  = $this->request->getQuery('startDate', 'string');
        $endDate    = $this->request->getQuery('endDate', 'string');

        $schoolId && $appName or die('缺少参数');

        //未指定时间则读取默认时间段
        $config = Main::getConfigByName('statsInfo');
        if(!$startDate && !$endDate) {
            $chartDays = $config['chartDays'] ? $config['chartDays'] : 30;
            $endDate = date('Y-m-d', time() - 24 * 3600);
            $startDate = date('Y-m-d', strtotime($endDate . "-{$chartDays} days"));
        }

        //连接数据库
        $appCode = XhsysConfig::findFirst([
            'conditions' => 'bDelete = 0 AND sSortName = "stats" AND sConfigExplain = ?0',
            'bind'       => ['统计_' . $appName]
        ])->sConfigName;
        $appCode = explode('_', $appCode);
        $appCode = end($appCode);
        $db = $this->connStatsDatabase($appCode);
        $db or die('数据库连接失败！');

        $fixInfo = $db->fetchAll("select iTchId,sTchName,SUM(iTaskFixNum) AS iTaskFixNum from XHApp_SchoolStats where iSchoolId = '{$schoolId}' and tTargetDate >= '{$startDate}' and tTargetDate <= '{$endDate}' group by iTchId");
        $this->view->setVar('fixInfo', $fixInfo);
    }

    /**
     * 登陆情况图表
     *
     * @param bool $more
     * @return bool
     *
     * create by ck 20170524
     */
    public function loginChartAction($more = true)
    {
        $this->view->pick('stats/loginChart');
        Assets::xhChart('js/stats/loginChart.js');
        UserPower::checkUserPower('Stats_App_LoginChart') or  die(Main::showMessageModal('对不起，您没有查看此页面的权限！'));

        //展示搜索条件
        if($more === true){
            $this->view->setTemplateBefore('loginChart');
            Main::showNavPosition('应用统计', '登陆情况');
        }
        return true;
    }

    /**
     * 根据条件获取登陆/未登录用户数
     *
     * create by ck 20170103
     * modify by ck 20170228    去除70ip
     * modify by ck 20170516    更改用户类型
     * modify by ck 20170524    更改用户类型为数组
     */
    public function getChartTotalLoginAction()
    {
        set_time_limit(120);
        $this->view->disable();
        if(APP_DEV){
            return $this->response->setJsonContent([
                'series' => [
                    ['name'=>'登陆情况', 'source'=> 'login']
                ],
                'login' => [['name' => '登陆用户', 'value' => rand(0, 40000)], ['name' => '未登陆用户', 'value' => rand(0, 40000)]]
            ]);
        }
        $typeArr   = $this->request->getPost('userType');
        $userType  = implode(',', $typeArr);
        $startDate = $this->request->getPost('startDate', 'string');
        $endDate   = $this->request->getPost('endDate', 'string');

        //连接数据中心
        $dbConfig  = Main::getConfigByName('oldCenterDB');
        $centerDB  = new Mysql($dbConfig);

        //查找条件
        $schoolArr = $centerDB->fetchAll('select sy_id,sy_name3 from system_type where sy_type="szxx" and sy_name3<>"" and sy_id not in(3563,3614,3618,803,1341,1611,1689,900090009,2747)');
        $schoolInfoArr = [];
        foreach($schoolArr as $school){
            $schoolInfo = explode('|', $school['sy_name3']);
            if(count($schoolInfo) < 6) continue;
            $dbName = explode('/', $schoolInfo[1]);
            $dbName = end($dbName);
            if($dbName == 'xh_zjhzztxx_school') continue;
            $dbIp = end($schoolInfo);
            if($dbIp == '172.16.10.70') continue;
            if($dbIp == '172.16.10.20') {
                $dbIp = '172.16.10.21';
            }
            elseif($dbIp == '172.16.10.22'){
                $dbIp = '172.16.10.23';
            }
            $schoolInfoArr[$school['sy_id']] = ['dbName' => $dbName, 'dbIp' => $dbIp];
        }
        $userCountSql  = "select count(us_id) as count from users where (us_xk_flag = '0' or us_xk_flag = '40002')";
        $loginCountSql = "select count(DISTINCT(us_id)) as count from :schoolDBName:.login_log,:schoolDBName:.users where us_id = lo_us_id and (us_xk_flag = '0' or us_xk_flag = '40002')";

        //添加用户类型及开始结束时间条件
        if(!in_array('0', $typeArr)){
            $userCountSql  .= " and us_flag in ({$userType})";
            $loginCountSql .= " and us_flag in ({$userType})";
        }
        else{
            if(!in_array('1', $typeArr)){
                $userCountSql  .= " and us_flag <> 1";
                $loginCountSql .= " and us_flag <> 1";
            }
            if(!in_array('4', $typeArr)){
                $userCountSql  .= " and us_flag <> 4";
                $loginCountSql .= " and us_flag <> 4";
            }
        }
//        if($userType){
//            $userCountSql  .= " and us_flag in ({$userType})";
//            $loginCountSql .= " and us_flag in ({$userType})";
//        }
        if($startDate){
            $loginCountSql .= " and lo_date >= '{$startDate}'";
        }
        if($endDate){
            $endDate = date('Y-m-d H:i:s', strtotime($endDate . '+1 day'));
            $loginCountSql .= " and us_date <= '{$endDate}'";
        }

        //计算符合条件总用户数
        $totalCount = $centerDB->fetchOne($userCountSql);
        $totalCount = $totalCount['count'];

        $dbArr = [];
        $loginCount = 0;
        foreach ($schoolInfoArr as $schoolId => $schoolInfo) {
            if(!$dbArr[$schoolInfo['dbIp']]){
                $dbArr[$schoolInfo['dbIp']] = new Mysql([
                    'host'      => $schoolInfo['dbIp'],
                    'username'  => 'readonly',
                    'password'  => 'lVf641AO',
                    'dbname'    => $schoolInfo['dbName'],
                    'charset'   => 'latin1'
                ]);
            }
            $result = $dbArr[$schoolInfo['dbIp']]->fetchOne(str_replace(':schoolDBName:', $schoolInfo['dbName'], $loginCountSql));
            if($result){
                $loginCount += $result['count'];
            }
        }
        return $this->response->setJsonContent([
            'series' => [
                ['name' => '登陆情况', 'source' => 'login']
            ],
            'login'  => [
                ['name' => '登陆用户',   'value' => $loginCount],
                ['name' => '未登陆用户', 'value' => ($totalCount - $loginCount)]
            ]
        ]);
    }

    /**
     * 获取应用版本号信息
     *
     * @param int $ver 版本号
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20161228
     * modify by ck 20161230
     * modify by ck 20170523    添加cookie写入，去除缓存
     * modify by ck 20170916    增加3.0平台统计
     */
    public function getChartSchoolAppAction($ver = 2)
    {
        $appInfo = [];
        if ($ver == 3) {
            $packageName = $this->request->getPost('packageName', 'string');
            $this->cookies->set('schoolAppVer3_' . Main::getLoginUserInfo('userId'), base64_encode(implode(',', $packageName)), time() + 3600 * 24 * 365)->send();
            $httpClient = new HttpClient(Main::getConfigByName('jAppServer')['url']);
            $response = $httpClient->postJson('/api/v1/app/assigned/schools/statistics', ['packageNames' => $packageName]);
            if (!$response->isSuccess()) {
                return $this->sendErrorResponse(500, '获取失败', $response);
            }
            $appList = $response->toArray();

            //计算版本最大数量
            $verMaxCount = 0;
            foreach ($appList as $app) {
                if (count($app['versionAssignedSchools']) > $verMaxCount) {
                    $verMaxCount = count($app['versionAssignedSchools']);
                }
            }

            //组合数据
            foreach ($appList as $app) {
                $appInfo['xList'][] = $app['appName'] . '-' . $this->schoolAppEnum['userType'][$app['userType']];
                for ($i = 1; $i <= $verMaxCount; $i++) {
                    $appInfo['yList' . $i][] = isset($app['versionAssignedSchools'][$i - 1]['schoolNum']) ? $app['versionAssignedSchools'][$i - 1]['schoolNum'] : 0;
                }
            }
            for ($i = 1; $i <= $verMaxCount; $i++) {
                $appInfo['series'][] = ['name' => '版本' . $i, 'source' => 'yList' . $i];
            }
        }
        else {
            $appName = $this->request->getPost('appName', 'string');
            $this->cookies->set('schoolAppVer2_' . Main::getLoginUserInfo('userId'), base64_encode(implode(',', $appName)), time() + 3600 * 24 * 365)->send();
            if ($appName) {
                $appName = implode('","', $appName);
            }
            try {
                $dbConfig = Main::getConfigByName('oldCenterDB');
                $db = new Mysql($dbConfig);
                $verCount = $db->fetchAll('SELECT count(DISTINCT(app_version)) as count FROM SchoolAppUpdateInfo WHERE app_name IN ("' . $appName . '") GROUP BY app_name');
                $verCount = array_column($verCount, 'count');
                $verMaxCount = max($verCount);
                $appNameInfo = [];
                $appNameVerInfo = $db->fetchAll('SELECT app_name,app_version,count(school_id) as count FROM `SchoolAppUpdateInfo` WHERE app_name IN ("' . $appName . '") GROUP BY app_name,app_version');
            }
            catch (\Exception $e) {
                return $this->sendErrorResponse(500, $e->getMessage());
            }
            foreach ($appNameVerInfo as $info) {
                $appNameInfo[$info['app_name']][] = intval($info['count']);
            }
            foreach ($appNameInfo as $key => $info) {
                $appInfo['xList'][] = $key;
                for ($i = 1; $i <= $verMaxCount; $i++) {
                    $appInfo['yList' . $i][] = isset($info[$i - 1]) ? $info[$i - 1] : 0;
                }
            }
            for ($i = 1; $i <= $verMaxCount; $i++) {
                $appInfo['series'][] = ['name' => '版本' . $i, 'source' => 'yList' . $i];
            }
        }
        return $this->response->setJsonContent($appInfo);
    }

    /**
     * 根据应用名展开版本数量详情
     *
     * create by ck 20170103
     * modify by ck 20170105    展示学校列表及合计
     * modify by ck 20171012    2.0学校名称从库中获取
     */
    public function schoolSingleAppInfoAction()
    {
        $this->view->pick('stats/schoolSingleAppInfo');
        $ver     = $this->request->getQuery('ver', 'int');
        $appName = $this->request->getQuery('appName', 'string');
        if (!$appName || !$ver) {
            return $this->sendViewError('缺少参数');
        }
        $httpClient = new HttpClient(Main::getConfigByName('jAppServer')['url']);
        $appInfo    = [];
        $schoolList = XhschoolInfo::getSchoolArray();
        if ($ver == 3) {
            $appName    = explode('-', $appName);
            $userType   = array_search(end($appName), $this->schoolAppEnum['userType']);

            //根据名称及类型包名信息
            $response = $httpClient->get('/api/v1/app/brief/info', ['name' => $appName[0], 'userType' => $userType]);
            if (!$response->isSuccess()) {
                return $this->sendViewError('接口调用失败:' . json_encode($response));
            }
            $packageName = $response->toArray()['packageName'];

            //获取信息并组合
            $response = $httpClient->get('/api/v1/app/assigned/schools', ['packageName' => $packageName, 'cache' => true]);
            if (!$response->isSuccess()) {
                return $this->sendViewError('接口调用失败:' . json_encode($response));
            }
            $body = $response->toArray();
            $this->view->setVar('lastVersion', ['versionCode' => $body['latestVersionCode'], 'versionName' => $body['latestVersionName']]);
            $versionList = $body['versionAssignedSchools'];
            foreach ($versionList as $version) {
                foreach ($version['schools'] as $schoolId) {
                    $appInfo[$version['versionName']][] = $schoolList[$schoolId] ?: $schoolId;
                }
            }
        }
        else {
            $dbConfig = Main::getConfigByName('oldCenterDB');
            $db     = new Mysql($dbConfig);
            $appArr = $db->fetchAll("select app_version,school_id,school_name from SchoolAppUpdateInfo where app_name = '{$appName}' order by app_version");
            foreach($appArr as $app){
//                $appInfo[$app['app_version']][] = $app['school_name'];
                $appInfo[$app['app_version']][] = $schoolList[$app['school_id']] ?: $app['school_id'];
            }

            //获取最新版本
            $userType = 4;
            if (strpos($appName, '(')) {
                $appName  = explode('(' , $appName);
                $userType = array_search(trim(end($appName), ')'), $this->schoolAppEnum['userType']);
                $appName  = $appName[0];
            }
            $response = $httpClient->get('/api/v1/app/brief/info', ['name' => $appName, 'userType' => $userType]);
            if ($response->isSuccess()) {
                $packageName = $response->toArray()['packageName'];
                //获取信息并组合
                $response = $httpClient->get('/api/v1/app/assigned/schools', ['packageName' => $packageName, 'cache' => true]);
                if ($response->isSuccess() && $response->toArray()) {
                    $body = $response->toArray();
                    $this->view->setVar('lastVersion', ['versionCode' => $body['latestVersionCode'], 'versionName' => $body['latestVersionName']]);
                }
            }
        }
        return $this->view->setVar('appInfo', $appInfo);
    }

    /**
     * 各应用学校使用情况总览
     *
     * create by ck 20170517
     */
    public function appStatsOverviewAction()
    {
        $this->view->pick('stats/appStatsOverview');
        Assets::easyUI('js/stats/appStatsOverview.js');
        $listSearchArr = [];
        $listSearchArr[] = ['type'=>'select', 'class'=>'easyui-combobox', 'id'=>'List_Search_Option', 'data' => ['' => '总量/平均', 'sum' => '总量', 'avg' => '平均']];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datebox', 'id'=>'List_Search_StartTime', 'label'=>' 开始时间：', 'required'=>'required'];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datebox', 'id'=>'List_Search_EndTime', 'label'=>' 截止时间：', 'required'=>'required'];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-textbox', 'id'=>'List_Search_SchoolName', 'label'=> ' 学校名称：'];
        $listSearchArr[] = ['type'=>'button', 'class'=>'easyui-linkbutton', 'id'=>'bt_list_search', 'text'=>'查看', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        $listSearchArr[] = ['type'=>'button', 'class'=>'easyui-linkbutton', 'id'=>'bt_list_Export', 'text'=>'导出Excel', 'icon'=>'fa-file-excel-o', 'style'=>'margin-left:10px'];
        $this->view->setVars(array(
            'List'      => Template::createList('List', 'stats/XHStats_AppStatsOverview', [
                'checkbox'      => false,
                'searchToolbar' => Template::createSearchToolBar($listSearchArr)
            ])
        ));
    }

    /**
     * 获取各学校应用总览数据
     *
     * @param bool $return
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170517
     * modify by ck 20170518    添加筛选学校功能，添加总量/平均选择查看功能
     * modify by ck 20170608    添加排序，总量/平均分开排序
     */
    public function getAppStatsOverviewAction($return = false)
    {
        $this->view->disable();
        $startTime  = $this->request->get('iStartTime', 'string');
        $endTime    = $this->request->get('iEndTime', 'string');
        $schoolName = $this->request->get('sSchoolName', 'string');
        $option     = $this->request->get('option', 'string');
        $sort       = $this->request->get('sort', 'string');
        $order      = $this->request->get('order', 'string');

        //计算分页相应数据并获取学校列表
        $allowSchoolIds = School::getPower();
        $allowSchoolIds or die(json_encode(['count' => 0, 'rows' => [], 'error' => '无学校权限']));
        $number = Main::getPageNumInfo('rows');
        $offset = Main::getPageNumInfo('offset');
        $schoolNameArr = XhschoolInfo::getSchoolSupportArray();
        foreach([803,1341,1611,1689,3563,3614,3816,900090009,2747,4160] as $schId){
            unset($schoolNameArr[$schId]);
        }
        $schoolArr = array_keys($schoolNameArr);
        $allowSchoolIds !== true and $schoolArr = array_intersect($schoolArr, $allowSchoolIds);

        //筛选学校
        $schoolCondition = '';
        if(($schoolName = trim($schoolName)) != ''){
            $searchSchoolId = [];
            foreach($schoolNameArr as $key => $value){
                if(strstr($value, $schoolName)){
                    $searchSchoolId[] = $key;
                }
            }
            if(empty($searchSchoolId)){
                die(json_encode(['count' => 0, 'rows' => [], 'error' => '无学校可筛选']));
            }
            else{
                $schoolArr = array_intersect($schoolArr, $searchSchoolId);
            }
        }

        //获取应用编号列表
        $appArr     = $this->getStatsAppInfo();
        $appCodeArr = array_keys($appArr);

        //如需排序，则处理排序字段并排序应用编号，否则计算总数，立即截取需获取学校ID，处理学校过滤条件
        $count = count($schoolArr);
        $rowsSortField = $sortAppCode = $sortFieldType = '';
        if($sort) {
            $sortField     = explode('_', $sort);
            $sortFieldType = $sortField[1];
            $sortAppCode   = $sortField[0];
            unset($appCodeArr[array_search($sortAppCode, $appCodeArr)]);
            array_unshift($appCodeArr, $sortAppCode);
        }
        else {
            $return or $schoolArr = array_slice($schoolArr, $offset, $number);
            $schoolIds = implode(',', $schoolArr);
            $schoolCondition .= " AND iSchoolId IN ({$schoolIds})";
        }

        //预处理数据
        $rows = [];
        foreach($schoolArr as $schId){
            $rows[$schId] = ['iSchoolId' => $schId, 'sSchoolName' => $schoolNameArr[$schId]];
        }

        //遍历应用
        foreach($appCodeArr as $appCode){
            $statsConfig = Main::getConfigByName('stats_' . $appCode);
            $statsConfig or die;
            $statsConfig = explode('|', $statsConfig['readDB']);
            try{
                $conn = new Mysql([
                    'host'      => $statsConfig[0],
                    'username'  => $statsConfig[1],
                    'password'  => $statsConfig[2],
                    'dbname'    => $statsConfig[3],
                    'charset'   => $statsConfig[4]
                ]);
            }
            catch(\Exception $e){
                continue;
            }
            switch($appCode){
                case 'CA103001':
                case 'CA104001': {
                    $columns = '
                          COUNT(DISTINCT(iTchId)) AS iTchNum,
                          SUM(iTaskFixNum) AS iTaskFixNum';
                    break;
                }
                case '1500': {
                    $columns = '
                          COUNT(DISTINCT(iTchId)) AS iTchNum,
                          SUM(iTaskFixNum) AS iTaskFixNum,
                          FORMAT((SUM(iStuNum)/COUNT(sClassId))*COUNT(DISTINCT(sClassId)),0) AS iStuNum,
                          SUM(iPracticeNum) AS iPracticeNum';
                    break;
                }
                case 'CA101003': {
                    $columns = '
                          COUNT(DISTINCT(iTchId)) AS iTchNum,
                          SUM(iTaskFixNum) AS iTaskFixNum,
                          FORMAT((SUM(iStuNum)/COUNT(sClassId))*COUNT(DISTINCT(sClassId)),0) AS iStuNum,
                          SUM(iPracticeNum) AS iPracticeNum,
                          SUM(iSumNum) AS iSumNum';
                    break;
                }
                case 'CA101001':
                case 'CA101002':
                case 'CA101007':
                case 'CA101008': {
                    $columns = '
                              FORMAT((SUM(iStuNum)/COUNT(sClassId))*COUNT(DISTINCT(sClassId)),0) AS iStuNum,
                              SUM(iSumNum) AS iSumNum';
                    break;
                }
                case 'CA105002': {
                    $columns = '
                          FORMAT((SUM(iStuNum)/COUNT(sClassId))*COUNT(DISTINCT(sClassId)),0) AS iStuNum,
                          SUM(iPracticeNum) AS iPracticeNum';
                    break;
                }
                case 'CA105003': {
                    $columns = '
                          FORMAT((SUM(iStuNum)/COUNT(sClassId))*COUNT(DISTINCT(sClassId)),0) AS iStuNum,
                          SUM(iPracticeNum) AS iPracticeNum,
                          SUM(iTaskTimeCost) AS iTaskTimeCost';
                    break;
                }
                case 'CA101006': {
                    $columns = '
                          FORMAT((SUM(iStuNum)/COUNT(sClassId))*COUNT(DISTINCT(sClassId)),0) AS iStuNum,
                          SUM(iTaskTimeCost) AS iTaskTimeCost';
                    break;
                }
                default: continue 2;
            }
            $columns .= ',iSchoolId,MAX(tTargetDate) AS tLastDate';
            $query = "SELECT {$columns} FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}'{$schoolCondition} GROUP BY iSchoolId";

            //需排序且当前应用为排序应用
            if($sort && $appCode == $sortAppCode){
                //平均数作为排序依据
                if($option == 'avg'){
                    switch($sortFieldType){
                        case 'Fix': {
                            $rowsSortField = 'fAvgTaskFixNum';
                            $query .= " ORDER BY SUM(iTaskFixNum)/COUNT(DISTINCT(iTchId)) {$order}";
                            break;
                        }
                        case 'Practice': {
                            $rowsSortField = 'fAvgPracticeNum';
                            $query .= " ORDER BY SUM(iPracticeNum)/FORMAT((SUM(iStuNum)/COUNT(sClassId))*COUNT(DISTINCT(sClassId)),0) {$order}";
                            break;
                        }
                        case 'Brush': {
                            $rowsSortField = 'fAvgSumNum';
                            $query .= " ORDER BY SUM(iSumNum)/FORMAT((SUM(iStuNum)/COUNT(sClassId))*COUNT(DISTINCT(sClassId)),0) {$order}";
                            break;
                        }
                        case 'Duration': {
                            $rowsSortField = 'fAvgTimeCost';
                            $query .= " ORDER BY SUM(iTaskTimeCost)/FORMAT((SUM(iStuNum)/COUNT(sClassId))*COUNT(DISTINCT(sClassId)),0) {$order}";
                            break;
                        }
                    }
                }
                else{
                    switch($sortFieldType){
                        case 'Fix': {
                            $rowsSortField = 'iTaskFixNum';
                            $query .= " ORDER BY iTaskFixNum {$order}";
                            break;
                        }
                        case 'Practice': {
                            $rowsSortField = 'iPracticeNum';
                            $query .= " ORDER BY iPracticeNum {$order}";
                            break;
                        }
                        case 'Brush': {
                            $rowsSortField = 'fAvgSumNum';
                            $query .= " ORDER BY iSumNum {$order}";
                            break;
                        }
                        case 'Duration': {
                            $rowsSortField = 'iTaskTimeCost';
                            $query .= " ORDER BY iTaskTimeCost {$order}";
                            break;
                        }
                    }
                }
                $return or $query .= " LIMIT {$offset},{$number}";
            }

            $appSchInfo = $conn->fetchAll($query);
            foreach($appSchInfo as $info){
                $schId  = $info['iSchoolId'];
                if(!isset($rows[$schId])) continue;
                $tchNum = isset($info['iTchNum']) ? str_replace(',', '', $info['iTchNum']) : 0;
                $stuNum = isset($info['iStuNum']) ? str_replace(',', '', $info['iStuNum']) : 0;
                $rows[$schId]['tLastDate'] = $info['tLastDate'];

                //处理平均
                if(isset($info['iTaskFixNum']) && $tchNum){
                    $info['fAvgTaskFixNum'] = sprintf("%.2f", $info['iTaskFixNum'] / $tchNum);
                }
                if(isset($info['iPracticeNum']) && $stuNum){
                    $info['fAvgPracticeNum'] = sprintf("%.2f", $info['iPracticeNum'] / $stuNum);
                }
                if(isset($info['iSumNum']) && $stuNum){
                    $info['fAvgSumNum'] = sprintf("%.2f", $info['iSumNum'] / $stuNum);
                }
                if(isset($info['iTaskTimeCost']) && $stuNum){
                    $info['fAvgTimeCost'] = sprintf("%.2f", $info['iTaskTimeCost'] / $stuNum);
                }

                //处理数据到学校节点
                if(isset($info['iTaskFixNum']) && isset($info['fAvgTaskFixNum'])){
                    $rows[$schId][$appCode . '_Fix'] = $option == 'sum' ? $info['iTaskFixNum'] : ($option == 'avg' ? $info['fAvgTaskFixNum'] : $info['iTaskFixNum'] . '/' . $info['fAvgTaskFixNum']);
                }
                if(isset($info['iPracticeNum']) && isset($info['fAvgPracticeNum'])){
                    $rows[$schId][$appCode . '_Practice'] = $option == 'sum' ? $info['iPracticeNum'] : ($option == 'avg' ? $info['fAvgPracticeNum'] : $info['iPracticeNum'] . '/' . $info['fAvgPracticeNum']);
                }
                if(isset($info['iSumNum']) && isset($info['fAvgSumNum'])){
                    $rows[$schId][$appCode . '_Brush'] = $option == 'sum' ? $info['iSumNum'] : ($option == 'avg' ? $info['fAvgSumNum'] : $info['iSumNum'] . '/' . $info['fAvgSumNum']);
                }
                if(isset($info['iTaskTimeCost']) && isset($info['fAvgTimeCost'])){
                    $info['iTaskTimeCost'] = Tool::secondToTime($info['iTaskTimeCost']);
                    $info['fAvgTimeCost'] = Tool::secondToTime($info['fAvgTimeCost']);
                    $rows[$schId][$appCode . '_Duration'] = $option == 'sum' ? $info['iTaskTimeCost'] : ($option == 'avg' ? $info['fAvgTimeCost'] : $info['iTaskTimeCost'] . '/' . $info['fAvgTimeCost']);
                }

                //添加需排序字段
                ($sort && $appCode == $sortAppCode && $rowsSortField) and $rows[$schId][$rowsSortField] = $info[$rowsSortField];
            }
            //执行排序
            if($sort && $appCode == $sortAppCode){
                $sortSchoolId = [];
                foreach($rows as $key => $info){
                    $sortSchoolId[$key] = $info[$rowsSortField];
                    $sortSchoolId[$key] or $sortSchoolId[$key] = 0;
                }
                //处理分页学校ID
                array_multisort($sortSchoolId, $order == 'desc' ? SORT_DESC : SORT_ASC, $rows);
                $return or $rows = array_slice($rows, $offset, $number);
                $rows = array_column($rows, null, 'iSchoolId');
                $schoolIds = implode(',', array_keys($rows));
                $schoolCondition .= " AND iSchoolId IN ({$schoolIds})";
            }
        }
        if($return){
            return array_values($rows);
        }
        return $this->response->setJsonContent(['total' => $count, 'rows' => array_values($rows)]);
    }

    /**
     * 导出个应用情况总览excel表
     *
     * create by ck 20170518
     */
    public function exportAppStatsOverviewAction()
    {
        $this->view->disable();
        $startTime  = $this->request->get('iStartTime', 'string');
        $endTime    = $this->request->get('iEndTime', 'string');
        $schoolName = $this->request->get('sSchoolName', 'string');
        $source = $this->getAppStatsOverviewAction(true);
        $source or die('无数据可导出');
        $title = [
            'iSchoolId'             => '学校ID',
            'sSchoolName'           => '学校名称',
            'CA103001_Fix'          => '云作业布置',
            '1500_Fix'              => '口语布置',
            '1500_Practice'         => '口语自练',
            'CA101003_Fix'          => '英刷布置',
            'CA101003_Brush'        => '英刷刷题',
            'CA101003_Practice'     => '英刷自练',
            'CA101001_Brush'        => '数刷刷题',
            'CA101002_Brush'        => '科刷刷题',
            'CA104001_Fix'          => '智通课堂布置',
            'CA101007_Brush'        => '写汉字刷题',
            'CA101008_Brush'        => '拼单词刷题',
            'CA105002_Practice'     => '美文阅读量',
            'CA105003_Practice'     => '悦读阅读量',
            'CA105003_Duration'     => '悦读时长',
            'CA101006_Duration'     => '听力时长',
            'tLastDate'             => '截止日期'
        ];
        $data = [];
        foreach($source as $key => $row){
            foreach($title as $field => $name){
                $data[$key][$field] = isset($row[$field]) ? $row[$field] : '';
            }
        }
        $fileName = '统计总览_' . $startTime . '_' . $endTime;
//        if($schoolName){
//            $fileName = $fileName . '_' . $schoolName;
//        }
        Tool::exportExcelOnline($fileName, $title, $data);
    }

    /**
     * 统计总表
     *
     * create by ck 20161108
     * modify by ck 20170516    云作业添加科目查看按钮
     */
    public function schoolOverviewAction()
    {
        $this->view->pick('stats/schoolOverview');
        Assets::easyUI();
        Assets::xhChart('js/stats/schoolOverview.js');
        $appCode = $this->request->getQuery('iAppCode', 'string');
        $listSearchArr = [];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datebox', 'id'=>'List_Search_StartTime', 'label'=>'开始时间：', 'required'=>'required'];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datebox', 'id'=>'List_Search_EndTime', 'label'=>' 截止时间：', 'required'=>'required'];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-textbox', 'id'=>'List_Search_SchoolName', 'label'=> ' 学校名称：'];
        $listSearchArr[] = ['type'=>'button', 'class'=>'easyui-linkbutton', 'id'=>'bt_list_search', 'text'=>'查看', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        $listSearchArr[] = ['type'=>'button', 'class'=>'easyui-linkbutton', 'id'=>'bt_list_Export', 'text'=>'导出Excel', 'icon'=>'fa-file-excel-o', 'style'=>'margin-left:10px'];
        $appCode == 'CA103001' and $listSearchArr[] = ['type'=>'button', 'class'=>'easyui-linkbutton', 'id'=>'bt_list_SeeSubject', 'text'=>'根据科目查看', 'icon'=>'fa-eye', 'style'=>'margin-left:10px'];
        $this->view->setVars(array(
            'List'      => Template::createList('List', 'stats/XHStats_SchoolOverview_' . $appCode, [
//                'checkbox'      => false,
                'searchToolbar' => Template::createSearchToolBar($listSearchArr)
            ]),
//            'appName'   => XhsysEnum::getEnumByNodeName('应用编号')[$appCode]
            'appName'   => $this->getStatsAppInfo()[$appCode]
        ));
    }

    /**
     * 获取总表数据
     *
     * @param bool $return
     * @return array|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20161108
     * modify by ck 20161129
     * modify by ck 20161212    更改数据库查询语句
     * modify by ck 20170104    添加学校名称筛选条件
     * modify by ck 20170219    添加用户权限判断展示的学校列表
     * modify by ck 20170220    更新口语训练条件
     * modify by ck 20170502    添加悦读统计（CA105003）
     * modify by ck 20170511    修改平均计算位置  SQL->PHP
     * modify by ck 20170601    取消学校ID排序，避免其它排序时混乱
     */
    public function getSchoolOverviewAction($return = false)
    {
        $this->view->disable();
        $appCode    = $this->request->get('iAppCode', 'string');
        $startTime  = $this->request->get('iStartTime', 'string');
        $endTime    = $this->request->get('iEndTime', 'string');
        $appCode && $startTime && $endTime or die;

        //获取允许用户访问的学校ID列表，如为true则不添加条件
        $allowSchoolIds = School::getPower();
        $schoolCondition = '';
        if(!$allowSchoolIds){
            die(json_encode(['total' => 0, 'rows' => []]));
        }
        elseif($allowSchoolIds !== true){
            $allowSchoolIds = implode(',', $allowSchoolIds);
            $schoolCondition = " AND iSchoolId IN ({$allowSchoolIds})";
        }

        //判断是否需要根据学校名称筛选
        $schoolName = $this->request->get('sSchoolName', 'string');
        if(trim($schoolName) != ''){
            $schoolId = [];
            $schoolArr = XhschoolInfo::getSchoolArray();
            foreach($schoolArr as $key => $value){
                if(strstr($value, $schoolName)){
                    $schoolId[] = $key;
                }
            }
            if(!$schoolId){
                $schoolCondition .= 'AND iSchoolId IN (0)';
            }
            else{
                $schoolId = implode(',', $schoolId);
                $schoolCondition .= "AND iSchoolId IN ({$schoolId})";
            }
        }

        $conn = $this->connStatsDatabase($appCode);
        $conn or die;
        $levelCondition = '';
        switch($appCode){
            case '1500': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$schoolCondition} GROUP BY iSchoolId",
                    'columns'   => 'iSchoolId,
                        COUNT(DISTINCT(sClassId)) AS iClassNum,
                        FORMAT((SUM(iStuNum)/COUNT(sClassId))*COUNT(DISTINCT(sClassId)),0) AS iStuNum,
                        COUNT(DISTINCT(sTchName)) AS iTchNum,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        SUM(iTaskUploadNum) AS iTaskUploadNum,
                        SUM(iTaskAllNum) AS iTaskAllNum,
                        FORMAT(SUM(iTaskUploadNum)/SUM(iTaskFixNum),2) AS fTaskUploadRate,
                        SUM(iPracticeNum) AS iPracticeNum,
                        SUM(iSumNum) AS iSumNum,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA103001': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$schoolCondition} GROUP BY iSchoolId,sSubject",
                    'columns'   => 'iSchoolId,
                        sSubject,
                        MAX(iSchStuNum) AS iSchStuNum,
                        COUNT(DISTINCT(sClassId)) AS iClassNum,
                        COUNT(DISTINCT(iTchId)) AS iTchNum,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        SUM(iTaskWrongNum) AS iTaskWrongNum,
                        SUM(iTaskAssignNum) AS iTaskAssignNum,
                        SUM(iTaskUploadNum) AS iTaskUploadNum,
                        SUM(iTaskAllNum) AS iTaskAllNum,
                        FORMAT(100*SUM(iTaskUploadNum)/SUM(iTaskAssignNum),2) AS fTaskUploadRate,
                        FORMAT(100*SUM(iTaskCorrectNum)/SUM(iTaskAssignNum),2) AS fTaskCorrectRate,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA103001-3': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$schoolCondition} GROUP BY iSchoolId,sSubject",
                    'columns'   => 'iSchoolId,
                        sSubject,
                        COUNT(DISTINCT(sClassId)) AS iClassNum,
                        COUNT(DISTINCT(iTchId)) AS iTchNum,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        SUM(iTaskWrongNum) AS iTaskWrongNum,
                        SUM(iTaskAssignNum) AS iTaskAssignNum,
                        SUM(iTaskUploadNum) AS iTaskUploadNum,
                        SUM(iTaskAllNum) AS iTaskAllNum,
                        SUM(iTaskTotalNum) AS iTaskTotalNum,
                        SUM(iSumNum) AS iSumNum,
                        FORMAT(100*SUM(iTaskUploadNum)/SUM(iTaskAssignNum),2) AS fTaskUploadRate,
                        FORMAT(100*SUM(iTaskCorrectNum)/SUM(iTaskAssignNum),2) AS fTaskCorrectRate,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA101002':
            case 'CA101001': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$schoolCondition} GROUP BY sSubject,iSchoolId",
                    'columns'   => 'iSchoolId,
                        MAX(iSchStuNum) AS iSchStuNum,
                        COUNT(DISTINCT(sClassId)) AS iClassNum,
                        COUNT(DISTINCT(iTchId)) AS iTchNum,
                        SUM(iSumNum) AS iSumNum,
                        SUM(iRightNum) AS iRightNum,
                        FORMAT(100*SUM(iRightNum)/SUM(iSumNum), 2) AS fRightRate,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA101003': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$schoolCondition} GROUP BY iSchoolId",
                    'columns'   => 'iSchoolId,
                        MAX(iSchStuNum) AS iSchStuNum,
                        COUNT(DISTINCT(sClassId)) AS iClassNum,
                        FORMAT((SUM(iStuNum)/COUNT(sClassId))*COUNT(DISTINCT(sClassId)),0) AS iStuNum,
                        COUNT(DISTINCT(iTchId)) AS iTchNum,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        SUM(iTaskAssignNum) AS iTaskAssignNum,
                        SUM(iTaskAllNum) AS iTaskAllNum,
                        SUM(iTaskUploadNum) AS iTaskUploadNum,
                        FORMAT(SUM(iRightNum)/100,0) AS iRightNum,
                        FORMAT(SUM(iRightNum)/SUM(iTaskTotalNum), 2) AS fRightRate,
                        SUM(iSumNum) AS iSumNum,
                        FORMAT(100*SUM(iTaskUploadNum)/SUM(iTaskAssignNum),2) AS fTaskUploadRate,
                        SUM(iPracticeNum) AS iPracticeNum,
                        FORMAT(SUM(iPracticeRightNum)/SUM(iPracticeNum), 2) AS fPracticeRightRate,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA101003-3': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$schoolCondition} GROUP BY iSchoolId",
                    'columns'   => 'iSchoolId,
                        COUNT(DISTINCT(sClassId)) AS iClassNum,
                        FORMAT((SUM(iStuNum)/COUNT(sClassId))*COUNT(DISTINCT(sClassId)),0) AS iStuNum,
                        COUNT(DISTINCT(iTchId)) AS iTchNum,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        SUM(iTaskAssignNum) AS iTaskAssignNum,
                        SUM(iTaskAllNum) AS iTaskAllNum,
                        SUM(iTaskUploadNum) AS iTaskUploadNum,
                        FORMAT(SUM(iRightNum)/100,0) AS iRightNum,
                        FORMAT(SUM(iRightNum)/SUM(iTaskTotalNum), 2) AS fRightRate,
                        SUM(iSumNum) AS iSumNum,
                        FORMAT(100*SUM(iTaskUploadNum)/SUM(iTaskAssignNum),2) AS fTaskUploadRate,
                        SUM(iPracticeNum) AS iPracticeNum,
                        FORMAT(SUM(iPracticeRightNum)/SUM(iPracticeNum), 2) AS fPracticeRightRate,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA101006': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$schoolCondition} GROUP BY iSchoolId",
                    'columns'   => 'iSchoolId,
                        MAX(iSchStuNum) AS iSchStuNum,
                        COUNT(DISTINCT(sClassId)) AS iClassNum,
                        COUNT(DISTINCT(iTchId)) AS iTchNum,
                        SUM(iTaskTimeCost) AS iTaskTimeCost,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA101007':
            case 'CA101008': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$schoolCondition} GROUP BY iSchoolId",
                    'columns'   => 'iSchoolId,
                        MAX(iSchStuNum) AS iSchStuNum,
                        COUNT(DISTINCT(sClassId)) AS iClassNum,
                        COUNT(DISTINCT(iTchId)) AS iTchNum,
                        SUM(iSumNum) AS iSumNum,
                        SUM(iRightNum) AS iRightNum,
                        FORMAT(100*SUM(iRightNum)/SUM(iSumNum), 2) AS fRightRate,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA101009': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$schoolCondition} GROUP BY iSchoolId",
                    'columns'   => 'iSchoolId,
                        COUNT(DISTINCT(sClassId)) AS iClassNum,
                        COUNT(DISTINCT(iTchId)) AS iTchNum,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        SUM(iTaskAllNum) AS iTaskAllNum,
                        SUM(iTaskUploadNum) AS iTaskUploadNum,
                        SUM(iSumNum) AS iSumNum,
                        SUM(iPracticeNum) AS iPracticeNum,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA104001': {
                $levelCondition = ' AND iLevel = 0 ';
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$levelCondition} {$schoolCondition} GROUP BY sSubject,iSchoolId",
                    'columns'   => 'iSchoolId,
                        sSubject,
                        MAX(iSchStuNum) AS iSchStuNum,
                        COUNT(DISTINCT(sClassId)) AS iClassNum,
                        COUNT(DISTINCT(iTchId)) AS iTchNum,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA104001-3': {
                $levelCondition = ' AND iLevel = 3 ';
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$levelCondition} {$schoolCondition} GROUP BY sSubject,iSchoolId",
                    'columns'   => 'iSchoolId,
                        sSubject,
                        FORMAT((SUM(iStuNum)/COUNT(sClassId))*COUNT(DISTINCT(sClassId)),0) AS iStuNum,
                        COUNT(DISTINCT(sClassId)) AS iClassNum,
                        COUNT(DISTINCT(iTchId)) AS iTchNum,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        SUM(iTaskAllNum) AS iTaskAllNum,
                        SUM(iTaskWrongNum) AS iTaskWrongNum,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA105002': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$schoolCondition} GROUP BY iSchoolId",
                    'columns'   => 'iSchoolId,
                        MAX(iSchStuNum) AS iSchStuNum,
                        COUNT(DISTINCT(sClassId)) AS iClassNum,
                        FORMAT((SUM(iStuNum)/COUNT(sClassId))*COUNT(DISTINCT(sClassId)),0) AS iStuNum,
                        COUNT(DISTINCT(iTchId)) AS iTchNum,
                        SUM(iPracticeNum) AS iPracticeNum,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA105003': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$schoolCondition} GROUP BY iSchoolId",
                    'columns'   => 'iSchoolId,
                        COUNT(DISTINCT(sClassId)) AS iClassNum,
                        FORMAT((SUM(iStuNum)/COUNT(sClassId))*COUNT(DISTINCT(sClassId)),0) AS iStuNum,
                        COUNT(DISTINCT(iTchId)) AS iTchNum,
                        SUM(iPracticeNum) AS iPracticeNum,
                        SUM(iTaskTimeCost) AS iTaskTimeCost,
                        SUM(iCommentNum) AS iCommentNum,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            default: die(json_encode(['total' => 0, 'rows' => []]));
        }
        if($return){
            return $conn->fetchAll(str_replace(':columns:', $queryArr['columns'], $queryArr['query']));
        }
        //处理排序
        if($this->request->getPost('sort')){
            $queryArr['query'] .= " ORDER BY {$this->request->getPost('sort')} {$this->request->getPost('order')}";
        }
        $result = Main::runSqlPaginator($queryArr, $conn, true);
        XhschoolInfo::runSchoolName($result['rows']);

        //获取学校学生人数
        $schoolIds = array_column($result['rows'], 'iSchoolId');
        if ($schoolIds){
            $schoolIds    = implode(',', $schoolIds);
            $schoolStuNum = $conn->fetchAll("SELECT iSchoolId,sSubject,SUM(iStuNum) AS iStuNum FROM (SELECT * FROM (SELECT * FROM `XHApp_SchoolStats` WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId IN ($schoolIds) {$levelCondition} ORDER BY tTargetDate DESC) t GROUP BY sClassId,sSubject) t GROUP BY iSchoolId,sSubject");
            foreach ($schoolStuNum as $stuNum) {
                foreach ($result['rows'] as &$row) {
                    if ($row['iSchoolId'] == $stuNum['iSchoolId']
                        && (isset($row['sSubject']) ? $row['sSubject'] == $stuNum['sSubject'] : true)
                    ) {
                        $row['iStuNum'] = $stuNum['iStuNum'];
                    }
                }
            }
        }

        foreach($result['rows'] as &$row){
            $row['sSchoolName'] = "<font style='color: #0099CC'>{$row['sSchoolName']}</font>";

            //处理平均
            if(isset($row['iStuNum'])) {
                $studNum = str_replace(',', '', $row['iStuNum']);
                isset($row['iPracticeNum']) and $row['fAvgPracticeNum'] = round($row['iPracticeNum'] / $studNum, 2);
                isset($row['iTaskTimeCost']) and $row['fAvgTimeCost'] = round($row['iTaskTimeCost'] / $studNum, 2);
                isset($row['iCommentNum']) and $row['fAvgCommentNum'] = round($row['iCommentNum'] / $studNum, 2);
            }
            //处理时间
            isset($row['iTaskTimeCost']) and $row['iTaskTimeCost'] = Tool::secondToTime($row['iTaskTimeCost']);
            isset($row['fAvgTimeCost']) and $row['fAvgTimeCost'] = Tool::secondToTime($row['fAvgTimeCost']);
        }
        return $this->response->setJsonContent($result);
    }

    /**
     * 根据参数获取学校数据并导出excel表
     *
     * create by ck 20170104
     */
    public function exportSchoolOverviewAction()
    {
        $this->view->disable();
        $appCode    = $this->request->get('iAppCode', 'string');
        $startTime  = $this->request->get('iStartTime', 'string');
        $endTime    = $this->request->get('iEndTime', 'string');
        $schoolName = $this->request->get('sSchoolName', 'string');
        $titleArr = [
            'iSchoolId'         => '学校ID',
            'sSchoolName'       => '学校名称',
            'sSubject'          => '科目',
            'iClassNum'         => '班级数量',
            'iStuNum'           => '学生数量',
            'iTchNum'           => '教师数量',
            'iTaskFixNum'       => '布置次数',
            'iTaskAssignNum'    => '总布置数',
            'iTaskAllNum'       => '作业题量',
//            'iTaskUploadNum'    => '作业上传数',
            'iPracticeNum'      => '自练数量',
            'fAvgPracticeNum'   => '平均自练',
//            'fTaskUploadRate'   => '上传率',
//            'fTaskCorrectRate'  => '批改率',
            'iSumNum'           => '做题量',
            'tLastDate'         => '截止日期'
        ];
        $data = $this->getSchoolOverviewAction(true);
        $data or die('无数据可导出');
        XhschoolInfo::runSchoolName($data);

        $title = array_values($titleArr);
        $keys = array_keys($titleArr);
        foreach ($data as &$row) {
            $temp = [];
            foreach ($keys as $key) {
                $temp[$key] = $row[$key];
            }
            $row = $temp;
        }

//        $title = [];
//        foreach($data[0] as $key => $value){
//            $title[] = isset($titleArr[$key]) ? $titleArr[$key] : $key;
//        }
//        $fileName = XhsysEnum::getEnumByNodeName('应用编号')[$appCode] . '统计_' . $startTime . '_' . $endTime;
        $fileName = $this->getStatsAppInfo()[$appCode] . '统计_' . $startTime . '_' . $endTime;
//        if($schoolName){
//            $fileName = $fileName . '_' . $schoolName;
//        }
        Tool::exportExcelOnline($fileName, $title, $data);
    }

    /**
     * 获取学校应用使用情况走势数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170522
     * modify by ck 20170523    跨年份时添加年份信息，防止数据合并
     */
    public function getChartSchoolOverviewAction()
    {
        $this->view->disable();
        $appCode    = $this->request->get('iAppCode', 'string');
        $startTime  = $this->request->get('iStartTime', 'string');
        $endTime    = $this->request->get('iEndTime', 'string');
        $period     = $this->request->get('period', 'string');
        $schoolIds  = $this->request->get('schoolIds', 'string');

        //获取允许用户访问的学校ID列表，如为true则不添加条件
        $allowSchoolIds = School::getPower();
        $schoolCondition = '';
        if(!$allowSchoolIds){
            die;
        }
        elseif($allowSchoolIds !== true){
            $allowSchoolIds = implode(',', $allowSchoolIds);
            $schoolCondition = " AND iSchoolId IN ({$allowSchoolIds})";
        }

        //处理勾选学校条件
        if($schoolIds){
            $schoolCondition .= " AND iSchoolId IN ({$schoolIds})";
        }

        //处理所需统计项目字段名
        $statsItem  = $this->getNeedStatsItem($appCode);
        $itemFields = $groupFields = [];
        foreach($statsItem as $item){
            $itemFields[] = "SUM({$this->getSchoolChartInfo($item, 'field')}) AS `{$item}`";
        }

        //处理查询字段及分组字段
        $dateField  = 'tTargetDate';
        $yearField = '';
        if($period){
            //判断是否跨年
            $startYear = date('Y', strtotime($startTime));
            $endYear   = date('Y', strtotime($endTime));
            if($startYear != $endYear && $period != 'year'){
                $yearField     = "year({$dateField})";
                $itemFields[]  = $yearField;
                $groupFields[] = $yearField;
            }
            $dateField     = "{$period}({$dateField})";
        }
        $itemFields[]  = $dateField;
        $groupFields[] = $dateField;
        $itemFields    = implode(',', $itemFields);
        $groupFields   = implode(',', $groupFields);

        $conn   = $this->connStatsDatabase($appCode);
        $conn   or die;

        $query  = "SELECT {$itemFields} FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$schoolCondition} GROUP BY {$groupFields}";
        $result = $conn->fetchAll($query);

        //处理series及数据
        $chartData = [];
        foreach($result[0] as $key => $value){
            if($key == $dateField) continue;
            $chartData['series'][] = ['name' => $this->getSchoolChartInfo($key, 'name'), 'source' => $key];
        }
        foreach($result as $row){
            $year = '';
            if($yearField){
                $year = $row[$yearField] . '-';
            }
            foreach($row as $key => $value){
                if($key == $yearField) continue;
                if($key == $dateField) {
                    switch($period){
                        case 'week':    $chartData['xList'][] = "{$year}第{$value}周";  break;
                        case 'month':   $chartData['xList'][] = "{$year}{$value}月";    break;
                        case 'quarter': $chartData['xList'][] = "{$year}第{$value}季度";break;
                        case 'year':    $chartData['xList'][] = "{$value}年";           break;
                        default :       $chartData['xList'][] = $value;
                    }
                    continue;
                }
                $chartData[$key][] = $value;
            }
        }

        return $this->response->setJsonContent($chartData);
    }

    /**
     * 获取应用学校使用占比
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170525
     */
    public function getChartSchoolTrendAction()
    {
        $this->view->disable();
        $appCode    = $this->request->get('iAppCode', 'string');
        $startTime  = $this->request->get('iStartTime', 'string');
        $endTime    = $this->request->get('iEndTime', 'string');
        $schoolIds  = $this->request->get('schoolIds', 'string');

        //处理勾选学校条件
        $schoolCondition = '';
        if($schoolIds){
            $schoolCondition = " AND iSchoolId IN ({$schoolIds})";
        }
        else{
            //获取允许用户访问的学校ID列表，如为true则不添加条件
            $allowSchoolIds = School::getPower();
            if(!$allowSchoolIds){
                die;
            }
            elseif($allowSchoolIds !== true){
                $allowSchoolIds = implode(',', $allowSchoolIds);
                $schoolCondition = " AND iSchoolId IN ({$allowSchoolIds})";
            }
        }

        $conn = $this->connStatsDatabase($appCode);
        $conn  or die;

        $chartData = [];
        $statsItem = $this->getNeedStatsItem($appCode);
        foreach($statsItem as $item){
            $fieldName = $this->getSchoolChartInfo($item, 'field');
            $query     = "SELECT iSchoolId,SUM({$fieldName}) AS `{$item}` FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$schoolCondition} GROUP BY iSchoolId ORDER BY `{$item}` DESC";
            $schoolIds or $query .= ' LIMIT 10';
            $itemData  = $conn->fetchAll($query);
            XhschoolInfo::runSchoolName($itemData);
            $chartData['series'][] = ['name' => $this->getSchoolChartInfo($item, 'name'), 'source' => $item];
            foreach($itemData as $row){
                if(!$row[$item]) continue;
                $chartData[$item][] = ['name' => $row['sSchoolName'], 'value' => $row[$item]];
            }
        }
        return $this->response->setJsonContent($chartData);
    }

    /**
     * 学校科目分类统计表
     *
     * create by ck 20170516
     */
    public function schoolSubjectOverviewAction()
    {
        try {
            $this->view->pick('stats/schoolSubjectOverview');
            Assets::easyUI('js/stats/schoolSubjectOverview.js');
            $appCode = $this->request->getQuery('iAppCode', 'string');

            $conn = $this->connStatsDatabase($appCode);
            $conn or die;
            $subject = $conn->fetchAll('select distinct(sSubject) as sSubject from XHApp_SchoolStats');
            $subject = array_column($subject, 'sSubject', 'sSubject');

            $listSearchArr = [];
            $listSearchArr[] = ['type' => 'select', 'class' => 'easyui-combobox', 'id' => 'list_subject', 'editable' => 'false', 'data' => ['' => '--科目--'] + $subject];
            $listSearchArr[] = ['type' => 'text', 'class' => 'easyui-datebox', 'id' => 'list_start_time', 'label' => ' 开始时间：', 'required' => 'required'];
            $listSearchArr[] = ['type' => 'text', 'class' => 'easyui-datebox', 'id' => 'list_end_time', 'label' => ' 截止时间：', 'required' => 'required'];
            $listSearchArr[] = ['type' => 'text', 'class' => 'easyui-textbox', 'id' => 'list_school_name', 'label' => ' 学校名称：'];
            $listSearchArr[] = ['type' => 'button', 'class' => 'easyui-linkbutton', 'id' => 'bt_list_search', 'text' => '查看', 'icon' => 'fa-search', 'style' => 'margin-left:10px'];
            $this->view->setVars([
                'List' => Template::createList('list', 'stats/XHStats_SchoolSubjectOverview_' . $appCode, [
                    'checkbox' => false,
                    'searchToolbar' => Template::createSearchToolBar($listSearchArr)
                ]),
//            'appName'   => XhsysEnum::getEnumByNodeName('应用编号')[$appCode]
                'appName' => $this->getStatsAppInfo()[$appCode]
            ]);
        }
        catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 获取学校科目，教师信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170517
     */
    public function getSubjectOverviewDataAction()
    {
        $this->view->disable();
        $appCode    = $this->request->get('appCode', 'string');
        $startTime  = $this->request->get('startTime', 'string');
        $endTime    = $this->request->get('endTime', 'string');
        $appCode && $startTime && $endTime or die;
        $schoolName = $this->request->get('schoolName', 'string');
        $subject    = $this->request->get('subject', 'string');

        //获取允许用户访问的学校ID列表，如为true则不添加条件
        $allowSchoolIds = School::getPower();
        $schoolCondition = '';
        if(!$allowSchoolIds){
            die(json_encode(['total' => 0, 'rows' => []]));
        }
        elseif($allowSchoolIds !== true){
            $allowSchoolIds = implode(',', $allowSchoolIds);
            $schoolCondition = " AND iSchoolId IN ({$allowSchoolIds})";
        }

        //判断是否需要根据学校名称筛选
        if(trim($schoolName) != ''){
            $schoolId = [];
            $schoolArr = XhschoolInfo::getSchoolArray();
            foreach($schoolArr as $key => $value){
                if(strstr($value, $schoolName)){
                    $schoolId[] = $key;
                }
            }
            if(!$schoolId){
                $schoolCondition .= 'AND iSchoolId IN (0)';
            }
            else{
                $schoolId = implode(',', $schoolId);
                $schoolCondition .= "AND iSchoolId IN ({$schoolId})";
            }
        }

        //处理科目条件
        $subjectCondition = '';
        if($subject){
            $schoolCondition = " AND sSubject = '{$subject}'";
        }

        $conn = $this->connStatsDatabase($appCode);
        $conn or die;
        switch($appCode){
            case 'CA103001': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' {$schoolCondition}{$subjectCondition} GROUP BY iSchoolId,sSubject,iTchId order by iSchoolId",
                    'columns'   => 'iSchoolId,
                        sSubject,
                        iTchId,
                        sTchName,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        SUM(iTaskWrongNum) AS iTaskWrongNum,
                        SUM(iTaskAssignNum) AS iTaskAssignNum,
                        SUM(iTaskUploadNum) AS iTaskUploadNum,
                        SUM(iTaskAllNum) AS iTaskAllNum,
                        FORMAT(100*SUM(iTaskUploadNum)/SUM(iTaskAssignNum),2) AS fTaskUploadRate,
                        FORMAT(100*SUM(iTaskCorrectNum)/SUM(iTaskAssignNum),2) AS fTaskCorrectRate,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            default: die(json_encode(['total' => 0, 'rows' => []]));
        }
        //处理排序
        if($this->request->getPost('sort')){
            $queryArr['query'] .= " ORDER BY {$this->request->getPost('sort')} {$this->request->getPost('order')}";
        }
        $result = Main::runSqlPaginator($queryArr, $conn, true);
        XhschoolInfo::runSchoolName($result['rows']);
        foreach ($result['rows'] as &$row) {
            isset($row['iTaskFixNum']) and $row['iTaskFixNum'] = "<font style='color: #0099CC'>{$row['iTaskFixNum']}</font>";
        }
        return $this->response->setJsonContent($result);
    }

    /**
     * 单个学校情况统计页面
     *
     * create by ck 20161108
     */
    public function singleSchoolInfoAction()
    {
        $this->view->pick('stats/singleSchoolInfo');
        Assets::easyUI('js/stats/singleSchoolInfo.js');
        $appCode = $this->request->getQuery('iAppCode', 'string');
        $listSearchArr = [];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datebox', 'id'=>'List_Search_StartTime', 'label'=>'开始时间：', 'required'=>'required'];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datebox', 'id'=>'List_Search_EndTime', 'label'=>' 截止时间：', 'required'=>'required'];
        $listSearchArr[] = ['type'=>'select', 'id'=>'List_Search_Stage', 'multiple'=>'true', 'style'=>'width:150px;'];
        $listSearchArr[] = ['type'=>'button', 'class'=>'easyui-linkbutton', 'id'=>'bt_list_Export', 'text'=>'导出Excel', 'icon'=>'fa-file-excel-o', 'style'=>'margin-left:10px'];
        $listSearchArr[] = ['type'=>'button', 'class'=>'easyui-linkbutton', 'id'=>'bt_list_search', 'text'=>'查看', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        $this->view->setVars(array(
            'List'      => Template::createList('List', 'stats/XHStats_SingleSchool_' . $appCode, [
                'checkbox'      => false,
                'searchToolbar' => Template::createSearchToolBar($listSearchArr)
            ]),
//            'appName'   => XhsysEnum::getEnumByNodeName('应用编号')[$appCode],
            'appName'   => $this->getStatsAppInfo()[$appCode],
            'schoolName'=> XhschoolInfo::getSchoolArray()[$this->request->getQuery('iSchoolId', 'int')]
        ));
    }

    /**
     * 根据学校ID返回该学校期次信息
     *
     * create by ck 20170214
     */
    public function getSchoolStageListAction()
    {
        $this->view->disable();
        $schoolId = $this->request->getQuery('iSchoolId', 'int');
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '缺少学校id');
        }
        try {
            $dbName = null;
            $conn = Main::getSchoolMainDB($schoolId, $dbName);
            $stageSql = 'SELECT sy_id,sy_name FROM system_type where sy_type = "kkqcsz" and sy_state = 0';
            $stageArr = $conn->fetchAll($stageSql);
            $stageArr = array_column($stageArr, 'sy_name', 'sy_id');
            $stageInfo = [];
            foreach ($stageArr as $stageId => $stageName) {
                $sql = "select co_id from attendclass_time_class,course_list,class_list where cl_at_id=at_id and at_qc_id='{$stageId}' and cl_flag=1 and cl_co_id=co_id and co_typeflag=1 group by co_id order by co_ord";
                $coIdArr = $conn->fetchAll($sql);
                $coIds = implode(',', array_column($coIdArr, 'co_id'));
//            $coIds or $coIds = '0';
                $stageInfo[] = ['sStageName' => $stageName, 'sCoIds' => $coIds];
            }
            return $this->sendJsonResponse($stageInfo);
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取单个学校数据
     *
     * @param bool $return
     * @return array
     *
     * create by ck 20161108
     * modify by ck 20161129    数据来源更改
     * modify by ck 20161227    条件更改，时间戳改为日期
     * modify by ck 20170220    更新口语训练条件
     * modify by ck 20170502    添加悦读统计（CA105003）
     * modify by ck 20170511    修改平均计算位置  SQL->PHP
     */
    public function getSingleSchoolDataAction($return = false)
    {
        $this->view->disable();
        $appCode    = $this->request->get('iAppCode', 'string');
        $schoolId   = $this->request->get('iSchoolId', 'int');
        $startTime  = $this->request->get('iStartTime', 'string');
        $endTime    = $this->request->get('iEndTime', 'string');
        $coIds      = $this->request->get('coIds', 'string');
        $subject    = urldecode($this->request->get('sSubject', 'string'));
        $coIdCondition = '';
        $coIds and $coIdCondition = " AND iCoId IN ({$coIds})";
        $appCode && $schoolId && $startTime && $endTime or die;

        $statsConfig = Main::getConfigByName('stats_' . $appCode);
        $statsConfig or die;
        $statsConfig = explode('|', $statsConfig['readDB']);
        $conn = new Mysql([
            'host'      => $statsConfig[0],
            'username'  => $statsConfig[1],
            'password'  => $statsConfig[2],
            'dbname'    => $statsConfig[3],
            'charset'   => $statsConfig[4]
        ]);
        switch($appCode){
            case '1500': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = {$schoolId} GROUP BY sClassId",
                    'columns'   => 'sClassId,
                        sClassName,
                        FORMAT(SUM(iStuNum)/COUNT(sClassId),0) AS iStuNum,
                        sTchName,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        SUM(iTaskUploadNum) AS iTaskUploadNum,
                        SUM(iTaskAllNum) AS iTaskAllNum,
                        FORMAT(SUM(iTaskUploadNum)/SUM(iTaskFixNum),2) AS fTaskUploadRate,
                        SUM(iPracticeNum) AS iPracticeNum,
                        SUM(iSumNum) AS iSumNum,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA103001': {
                $subject or die;
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = {$schoolId} AND sSubject = '{$subject}'{$coIdCondition} GROUP BY sClassId",
                    'columns'   => 'iCoId,
                        sClassId,
                        sClassName,
                        sGradeName,
                        sSubject,
                        iTchId,
                        sTchName,
                        FORMAT(SUM(iStuNum)/COUNT(sClassId),0) AS iStuNum,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        SUM(iTaskWrongNum) AS iTaskWrongNum,
                        SUM(iTaskAssignNum) AS iTaskAssignNum,
                        SUM(iTaskUploadNum) AS iTaskUploadNum,
                        SUM(iTaskAllNum) AS iTaskAllNum,
                        FORMAT(100*SUM(iTaskUploadNum)/SUM(iTaskAssignNum),2) AS fTaskUploadRate,
                        FORMAT(100*SUM(iTaskCorrectNum)/SUM(iTaskAssignNum),2) AS fTaskCorrectRate,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA103001-3': {
                $subject or die;
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = {$schoolId} AND sSubject = '{$subject}' {$coIdCondition} GROUP BY sClassId,iTchId",
                    'columns'   => 'iCoId,
                        sClassId,
                        sClassName,
                        sSubject,
                        iTchId,
                        sTchName,
                        FORMAT(SUM(iStuNum)/COUNT(sClassId),0) AS iStuNum,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        SUM(iTaskWrongNum) AS iTaskWrongNum,
                        SUM(iTaskAssignNum) AS iTaskAssignNum,
                        SUM(iTaskUploadNum) AS iTaskUploadNum,
                        SUM(iTaskAllNum) AS iTaskAllNum,
                        FORMAT(100*SUM(iTaskUploadNum)/SUM(iTaskAssignNum),2) AS fTaskUploadRate,
                        FORMAT(100*SUM(iTaskCorrectNum)/SUM(iTaskAssignNum),2) AS fTaskCorrectRate,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA101001':
            case 'CA101002': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = {$schoolId}{$coIdCondition} GROUP BY sClassId",
                    'columns'   => 'iCoId,
                        sClassId,
                        sClassName,
                        sGradeName,
                        FORMAT(SUM(iStuNum)/COUNT(sClassId),0) AS iStuNum,
                        iTchId,
                        sTchName,
                        SUM(iSumNum) AS iSumNum,
                        SUM(iRightNum) AS iRightNum,
                        FORMAT(100*SUM(iRightNum)/SUM(iSumNum), 2) AS fRightRate,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA101003': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = {$schoolId}{$coIdCondition} GROUP BY sClassId",
                    'columns'   => 'iCoId,
                        sClassId,
                        sClassName,
                        sGradeName,
                        FORMAT(SUM(iStuNum)/COUNT(sClassId),0) AS iStuNum,
                        iTchId,
                        sTchName,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        SUM(iTaskAssignNum) AS iTaskAssignNum,
                        SUM(iTaskAllNum) AS iTaskAllNum,
                        SUM(iTaskUploadNum) AS iTaskUploadNum,
                        FORMAT(SUM(iRightNum)/100,0) AS iRightNum,
                        FORMAT(SUM(iRightNum)/SUM(iTaskTotalNum), 2) AS fRightRate,
                        SUM(iSumNum) AS iSumNum,
                        FORMAT(100*SUM(iTaskUploadNum)/SUM(iTaskAssignNum),2) AS fTaskUploadRate,
                        SUM(iPracticeNum) AS iPracticeNum,
                        FORMAT(SUM(iPracticeRightNum)/SUM(iPracticeNum), 2) AS fPracticeRightRate,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA101006': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = {$schoolId}{$coIdCondition} GROUP BY sClassId",
                    'columns'   => 'iCoId,
                        sClassId,
                        sClassName,
                        sGradeName,
                        FORMAT(SUM(iStuNum)/COUNT(sClassId),0) AS iStuNum,
                        iTchId,
                        sTchName,
                        SUM(iTaskTimeCost) AS iTaskTimeCost,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA101007':
            case 'CA101008': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = {$schoolId}{$coIdCondition} GROUP BY sClassId",
                    'columns'   => 'iCoId,
                        sClassId,
                        sClassName,
                        sGradeName,
                        FORMAT(SUM(iStuNum)/COUNT(sClassId),0) AS iStuNum,
                        iTchId,
                        sTchName,
                        SUM(iSumNum) AS iSumNum,
                        SUM(iRightNum) AS iRightNum,
                        FORMAT(100*SUM(iRightNum)/SUM(iSumNum), 2) AS fRightRate,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA101009': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = {$schoolId} GROUP BY sClassId",
                    'columns'   => 'sClassId,
                        sClassName,
                        FORMAT(SUM(iStuNum)/COUNT(sClassId),0) AS iStuNum,
                        iTchId,
                        sTchName,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        SUM(iTaskAllNum) AS iTaskAllNum,
                        SUM(iTaskUploadNum) AS iTaskUploadNum,
                        SUM(iSumNum) AS iSumNum,
                        SUM(iPracticeNum) AS iPracticeNum,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA104001': {
                $subject or die;
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = {$schoolId} AND iLevel = 0 AND sSubject = '{$subject}'{$coIdCondition} GROUP BY sClassId",
                    'columns'   => 'iCoId,
                        sClassId,
                        sClassName,
                        sGradeName,
                        sSubject,
                        FORMAT(SUM(iStuNum)/COUNT(sClassId),0) AS iStuNum,
                        iTchId,
                        sTchName,
                        SUM(iSumNum) AS iSumNum,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA104001-3': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = {$schoolId} AND iLevel = 3 GROUP BY sClassId",
                    'columns'   => 'sClassId,
                        sClassName,
                        FORMAT(SUM(iStuNum)/COUNT(sClassId),0) AS iStuNum,
                        iTchId,
                        sTchName,
                        SUM(iSumNum) AS iSumNum,
                        SUM(iTaskFixNum) AS iTaskFixNum,
                        SUM(iTaskAllNum) AS iTaskAllNum,
                        SUM(iTaskWrongNum) AS iTaskWrongNum,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA105002': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = {$schoolId}{$coIdCondition} GROUP BY sClassId",
                    'columns'   => 'iCoId,
                        sClassId,
                        sClassName,
                        sGradeName,
                        FORMAT(SUM(iStuNum)/COUNT(sClassId),0) AS iStuNum,
                        iTchId,
                        sTchName,
                        SUM(iPracticeNum) AS iPracticeNum,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            case 'CA105003': {
                $queryArr = [
                    'query'     => "SELECT :columns: FROM XHApp_SchoolStats WHERE tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = {$schoolId}{$coIdCondition} GROUP BY sClassId",
                    'columns'   => 'sClassId,
                        sClassName,
                        MAX(iStuNum) AS iStuNum,
                        iTchId,
                        sTchName,
                        SUM(iPracticeNum) AS iPracticeNum,
                        SUM(iTaskTimeCost) AS iTaskTimeCost,
                        SUM(iCommentNum) AS iCommentNum,
                        MAX(tTargetDate) AS tLastDate',
                ];
                break;
            }
            default: die(json_encode(['total' => 0, 'rows' => []]));
        }
        if($return){
            return $conn->fetchAll(str_replace(':columns:', $queryArr['columns'], $queryArr['query']));
        }
        //处理排序
        if($this->request->getPost('sort')){
            $queryArr['query'] .= " ORDER BY {$this->request->getPost('sort')} {$this->request->getPost('order')}";
        }
        $result = Main::runSqlPaginator($queryArr, $conn, true);
        foreach($result['rows'] as $key => $row){
            $result['rows'][$key]['sClassName']   = "<font style='color: #FF0033'>{$row['sClassName']}</font>";
            $result['rows'][$key]['iStuNum']      = "<font style='color: #FF0033'>{$row['iStuNum']}</font>";
            isset($result['rows'][$key]['iTaskFixNum']) and $result['rows'][$key]['iTaskFixNum'] = "<font style='color: #0099CC'>{$row['iTaskFixNum']}</font>";

            //处理平均
            if(isset($row['iStuNum'])) {
                $studNum = str_replace(',', '', $row['iStuNum']);
                isset($row['iPracticeNum']) and $result['rows'][$key]['fAvgPracticeNum'] = round($row['iPracticeNum'] / $studNum, 2);
                isset($row['iTaskTimeCost']) and $result['rows'][$key]['fAvgTimeCost'] = round($row['iTaskTimeCost'] / $studNum, 2);
                isset($row['iCommentNum']) and $result['rows'][$key]['fAvgCommentNum'] = round($row['iCommentNum'] / $studNum, 2);
            }
            //处理时间
            isset($result['rows'][$key]['iTaskTimeCost']) and $result['rows'][$key]['iTaskTimeCost'] = Tool::secondToTime($result['rows'][$key]['iTaskTimeCost']);
            isset($result['rows'][$key]['fAvgTimeCost']) and $result['rows'][$key]['fAvgTimeCost'] = Tool::secondToTime($result['rows'][$key]['fAvgTimeCost']);
        }
        Main::runUserNameById($result['rows'], ['iTchId' => 'sTchName'], true);
        return $this->response->setJsonContent($result);
    }

    /**
     * 根据参数获取单个学校班级数据并导出excel表
     *
     * create by ck 20170216
     * modify by ck 20180428    处理教师姓名
     */
    public function exportSingleSchoolDataAction()
    {
        $this->view->disable();
        $appCode = $this->request->get('iAppCode', 'string');
        $startTime = $this->request->get('iStartTime', 'string');
        $schoolId = $this->request->get('iSchoolId', 'int');
        $endTime = $this->request->get('iEndTime', 'string');
        $titleArr = [
            'iCoId' => '集合ID',
            'sClassId' => '班级ID',
            'sClassName' => '班级名称',
            'sGradeName' => '年级',
            'sSubject' => '科目',
            'iStuNum' => '学生数量',
            'iTchId' => '教师ID',
            'sTchName' => '教师姓名',
            'iTaskFixNum' => '布置次数',
            'iTaskAllNum' => '作业题量',
//            'iTaskUploadNum' => '作业上传数',
//            'fTaskUploadRate' => '上交率',
//            'iRightNum' => '正确数',
//            'fRightRate' => '正确率',
            'iPracticeNum' => '自练数量',
            'fAvgPracticeNum' => '平均自练',
//            'fTaskCorrectRate' => '批改率',
            'tLastDate' => '截止日期'
        ];
        $data = $this->getSingleSchoolDataAction(true);
        $data or die('无数据可导出');
        Main::runUserNameById($data, ['iTchId' => 'sTchName'], true);

        $title = array_values($titleArr);
        $keys = array_keys($titleArr);
        foreach ($data as &$row) {
            $temp = [];
            foreach ($keys as $key) {
                $temp[$key] = $row[$key];
            }
            $row = $temp;
        }

//        $title = [];
//        foreach ($data[0] as $key => $value) {
//            $title[] = isset($titleArr[$key]) ? $titleArr[$key] : $key;
//        }
//        $fileName = XhsysEnum::getEnumByNodeName('应用编号')[$appCode] . '统计_' . $startTime . '_' . $endTime;
        $fileName = $this->getStatsAppInfo()[$appCode] . '统计_' . $startTime . '_' . $endTime;
//        if ($schoolId) {
//            $fileName = $fileName . '_' . XhschoolInfo::getSchoolArray()[$schoolId];
//        }
        Tool::exportExcelOnline($fileName, $title, $data);
    }

    /**
     * 班级学生信息统计页面
     *
     * create by ck 20161108
     */
    public function classStuInfoAction()
    {
        $this->view->pick('stats/classStuInfo');
        Assets::easyUI('js/stats/classStuInfo.js');
        $appCode = $this->request->getQuery('iAppCode', 'string');
        $listSearchArr = [];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datebox', 'id'=>'List_Search_StartTime', 'label'=>'开始时间：', 'required'=>'required'];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datebox', 'id'=>'List_Search_EndTime', 'label'=>' 截止时间：', 'required'=>'required'];
        $listSearchArr[] = ['type'=>'button', 'class'=>'easyui-linkbutton', 'id'=>'bt_list_search', 'text'=>'查看', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        $this->view->setVars(array(
            'List'      => Template::createList('List', 'stats/XHStats_ClassStuInfo_' . $appCode, [
                'checkbox'      => false,
                'searchToolbar' => Template::createSearchToolBar($listSearchArr)
            ]),
//            'appName'   => XhsysEnum::getEnumByNodeName('应用编号')[$appCode],
            'appName'   => $this->getStatsAppInfo()[$appCode],
            'schoolName'=> XhschoolInfo::getSchoolArray()[$this->request->getQuery('iSchoolId', 'int')]
        ));
    }

    /**
     * 获取班级学生数据
     *
     * create by ck 20161108
     */
    public function getClassStuInfoDataAction()
    {
        $this->view->disable();
        $appCode    = $this->request->getPost('iAppCode', 'string');
        $classId    = $this->request->getPost('sClassId', 'string');
        $startTime  = $this->request->getPost('iStartTime', 'string');
        $endTime    = $this->request->getPost('iEndTime', 'string');
        $appCode && $classId && $startTime && $endTime or die;
//        $subject    = $this->request->getPost('sSubject', 'string');
        $schoolId   = $this->request->getPost('iSchoolId', 'int');
        $coId       = $this->request->getPost('iCoId', 'int');
//        $subject    = urldecode($subject);
        $conditions = [
            'sClassId'      => $classId,
            'iStartTime'    => $startTime,
            'iEndTime'      => $endTime
        ];
//        if($subject){
//            $conditions['sSubject'] = $subject;
//        }
        if($schoolId){
            $conditions['iSchoolId'] = $schoolId;
        }
        if($coId){
            $conditions['iCoId'] = $coId;
        }
        $data = $this->getStatsData($appCode, 'classStuInfo', $conditions);
        $data = json_decode($data, true);
        foreach($data['rows'] as $key => $value){
            isset($data['rows'][$key]['sStuName']) and $data['rows'][$key]['sStuName'] = "<font style='color: #FF0033'>{$value['sStuName']}</font>";
            isset($data['rows'][$key]['iTaskNum']) and $data['rows'][$key]['iTaskNum'] = "<font style='color: #6633FF'>{$value['iTaskNum']}</font>";
            isset($data['rows'][$key]['iPracticeNum']) and $data['rows'][$key]['iPracticeNum'] = "<font style='color: #0099CC'>{$value['iPracticeNum']}</font>";
        }
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 班级作业情况页面
     *
     * create by ck 20161109
     */
    public function classTaskInfoAction()
    {
        $this->view->pick('stats/classTaskInfo');
        Assets::easyUI('js/stats/classTaskInfo.js');
        $appCode = $this->request->getQuery('iAppCode', 'string');
        $listSearchArr = [];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datebox', 'id'=>'List_Search_StartTime', 'label'=>'开始时间：', 'required'=>'required'];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datebox', 'id'=>'List_Search_EndTime', 'label'=>' 截止时间：', 'required'=>'required'];
        $listSearchArr[] = ['type'=>'button', 'class'=>'easyui-linkbutton', 'id'=>'bt_list_search', 'text'=>'查看', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        $this->view->setVars(array(
            'List'      => Template::createList('List', 'stats/XHStats_ClassTaskInfo_' . $appCode, [
                'checkbox'      => false,
                'searchToolbar' => Template::createSearchToolBar($listSearchArr)
            ]),
//            'appName'   => XhsysEnum::getEnumByNodeName('应用编号')[$appCode],
            'appName'   => $this->getStatsAppInfo()[$appCode],
            'schoolName'=> XhschoolInfo::getSchoolArray()[$this->request->getQuery('iSchoolId', 'int')]
        ));
    }

    /**
     * 获取班级作业情况
     *
     * create by ck 20161109
     */
    public function getClassTaskInfoDataAction()
    {
        $this->view->disable();
        $appCode    = $this->request->getPost('iAppCode', 'string');
        $classId    = $this->request->getPost('sClassId', 'string');
        $startTime  = $this->request->getPost('iStartTime', 'string');
        $endTime    = $this->request->getPost('iEndTime', 'string');
        $schoolId   = $this->request->getPost('iSchoolId', 'int');
        $coId       = $this->request->getPost('iCoId', 'int');
        $tchId      = $this->request->getPost('iTchId', 'int');
        if (!$appCode || !$startTime || !$endTime || (!$classId && !$tchId)) {
            return $this->sendViewError('缺少必要参数');
        }
        $conditions = [
            'sClassId'      => $classId,
            'iStartTime'    => $startTime,
            'iEndTime'      => $endTime
        ];
        if($schoolId){
            $conditions['iSchoolId'] = $schoolId;
        }
        if($coId){
            $conditions['iCoId'] = $coId;
        }
        if($tchId){
            $conditions['iTchId'] = $tchId;
        }

        echo $this->getStatsData($appCode, 'classTaskInfo', $conditions);
    }

    /**
     * 某次作业情况页面
     *
     * create by ck 20161108
     */
    public function singleTaskInfoAction()
    {
        $this->view->pick('stats/singleTaskInfo');
        Assets::easyUI('js/stats/singleTaskInfo.js');
        $appCode = $this->request->getQuery('iAppCode', 'string');
        $this->view->setVars(array(
            'List'      => Template::createList('List', 'stats/XHStats_SingleTaskInfo_' . $appCode, [
                'checkbox'      => false,
            ]),
//            'appName'   => XhsysEnum::getEnumByNodeName('应用编号')[$appCode],
            'appName'   => $this->getStatsAppInfo()[$appCode],
            'schoolName'=> XhschoolInfo::getSchoolArray()[$this->request->getQuery('iSchoolId', 'int')]
        ));
    }

    /**
     * 获取某次作业情况
     *
     * create by ck 20161108
     */
    public function getSingleTaskInfoAction()
    {
        $this->view->disable();
        $appCode    = $this->request->getPost('iAppCode', 'string');
        $classId    = $this->request->getPost('sClassId', 'string');
        $taskId     = $this->request->getPost('sTaskId', 'string');
        $appCode && $classId && $taskId or die;
        $schoolId   = $this->request->getPost('iSchoolId', 'int');
        $coId       = $this->request->getPost('iCoId', 'int');
        $conditions = [
            'sClassId'      => $classId,
            'sTaskId'       => $taskId
        ];
        if($schoolId){
            $conditions['iSchoolId'] = $schoolId;
        }
        if($coId){
            $conditions['iCoId'] = $coId;
        }
        echo $this->getStatsData($appCode, 'singleTaskInfo', $conditions);
    }

    /**
     * 单个学生作业情况页面
     *
     * create by ck 20161111
     */
    public function singleStuTaskAction()
    {
        $this->view->pick('stats/singleStuTask');
        Assets::easyUI('js/stats/singleStuTask.js');
        $appCode = $this->request->getQuery('iAppCode', 'string');
        $listSearchArr = [];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datebox', 'id'=>'List_Search_StartTime', 'label'=>'开始时间：', 'required'=>'required'];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datebox', 'id'=>'List_Search_EndTime', 'label'=>' 截止时间：', 'required'=>'required'];
        $listSearchArr[] = ['type'=>'button', 'class'=>'easyui-linkbutton', 'id'=>'bt_list_search', 'text'=>'查看', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        $this->view->setVars(array(
            'List'      => Template::createList('List', 'stats/XHStats_SingleStuTask_' . $appCode, [
                'checkbox'      => false,
                'searchToolbar' => Template::createSearchToolBar($listSearchArr)
            ]),
//            'appName'   => XhsysEnum::getEnumByNodeName('应用编号')[$appCode],
            'appName'   => $this->getStatsAppInfo()[$appCode],
            'schoolName'=> XhschoolInfo::getSchoolArray()[$this->request->getQuery('iSchoolId', 'int')]
        ));
    }

    /**
     * 获取单个学生作业情况
     *
     * create by ck 20161111
     */
    public function getSingleStuTaskAction()
    {
        $this->view->disable();
        $appCode    = $this->request->getPost('iAppCode', 'string');
        $classId    = $this->request->getPost('sClassId', 'string');
        $stuId      = $this->request->getPost('iStuId', 'int');
        $startTime  = $this->request->getPost('iStartTime', 'string');
        $endTime    = $this->request->getPost('iEndTime', 'string');
        $appCode && $classId && $stuId && $startTime && $endTime or die;
        $schoolId   = $this->request->getPost('iSchoolId', 'int');
        $coId       = $this->request->getPost('iCoId', 'int');
        $conditions = [
            'sClassId'   => $classId,
            'iStuId'     => $stuId,
            'iStartTime' => $startTime,
            'iEndTime'   => $endTime
        ];
        if($schoolId){
            $conditions['iSchoolId'] = $schoolId;
        }
        if($coId){
            $conditions['iCoId'] = $coId;
        }
        $data = $this->getStatsData($appCode, 'singleStuTask', $conditions);
        $data = json_decode($data, true);
        foreach($data['rows'] as $key => $value){
            isset($value['sTaskTitle']) and $data['rows'][$key]['sTaskTitle'] = "<font style='color: #FF0033'>{$value['sTaskTitle']}</font>";
        }
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 学生自练情况页面
     *
     * create by ck 20161110
     */
    public function singleStuPracticeAction()
    {
        $this->view->pick('stats/singleStuPractice');
        Assets::easyUI('js/stats/singleStuPractice.js');
        $listSearchArr = [];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datebox', 'id'=>'List_Search_StartTime', 'label'=>'开始时间：', 'required'=>'required'];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datebox', 'id'=>'List_Search_EndTime', 'label'=>' 截止时间：', 'required'=>'required'];
        $listSearchArr[] = ['type'=>'button', 'class'=>'easyui-linkbutton', 'id'=>'bt_list_search', 'text'=>'查看', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        $this->view->setVars(array(
            'List'      => Template::createList('List', 'stats/XHStats_SingleStuPractice', [
                'checkbox'      => false,
                'searchToolbar' => Template::createSearchToolBar($listSearchArr)
            ]),
//            'appName'   => XhsysEnum::getEnumByNodeName('应用编号')[$this->request->getQuery('iAppCode', 'string')],
            'appName'   => $this->getStatsAppInfo()[$this->request->getQuery('iAppCode', 'string')],
            'schoolName'=> XhschoolInfo::getSchoolArray()[$this->request->getQuery('iSchoolId', 'int')]
        ));
    }

    /**
     * 获取学生自练情况
     *
     * create by ck 20161110
     */
    public function getSingleStuPracticeDataAction()
    {
        $this->view->disable();
        $appCode    = $this->request->getPost('iAppCode', 'string');
        $classId    = $this->request->getPost('sClassId', 'string');
        $stuId      = $this->request->getPost('iStuId', 'int');
        $startTime  = $this->request->getPost('iStartTime', 'string');
        $endTime    = $this->request->getPost('iEndTime', 'string');
        $classId && $stuId && $startTime && $endTime or die;
        $data = $this->getStatsData($appCode, 'singleStuPractice', [
            'sClassId'   => $classId,
            'iStuId'     => $stuId,
            'iStartTime' => $startTime,
            'iEndTime'   => $endTime
        ]);
        $data = json_decode($data, true);
        foreach($data['rows'] as $key => $value){
            $data['rows'][$key]['iScore'] = "<font style='color: #FF0033'>{$value['iScore']}</font>";
        }
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 根据应用，数据类型获取相应数据并返回
     *
     * @param $appCode      --应用编号
     * @param $dataType     --数据类型
     * @param $conditions   --条件数组（K）
     * @return string
     *
     * create by ck 20161110
     * modify by ck 20170503    悦读独立出不同方式，http类更改
     */
    private function getStatsData($appCode, $dataType, $conditions)
    {
        $javaAppCode = ['CA105003'];
        $statsConfig = Main::getConfigByName('stats_' . $appCode);
        $httpClient = new HttpClient($statsConfig['url']);
        if(in_array($appCode, $javaAppCode)){
            $newConditions = [];
            isset($conditions['iStartTime']) and $newConditions['startTime'] = $conditions['iStartTime'] . ' 00:00:00';
            isset($conditions['iEndTime']) and $newConditions['endTime'] = date('Y-m-d H:i:s', strtotime($conditions['iEndTime'] . ' +1 day'));
            isset($conditions['sClassId']) and $newConditions['classId'] = $conditions['sClassId'];

            $path = $statsConfig['path_' . $dataType];
            isset($newConditions['classId']) and $path = str_replace('{classId}', $newConditions['classId'], $path);
            $response = $httpClient->get($path, $newConditions);
            $result = $response->toArray();
            if (!$result) {
                return json_encode(['total' => 0, 'rows' => [], 'error' => $response]);
            }
        }
        else {
            isset($conditions['iStartTime']) and $conditions['iStartTime'] = strtotime($conditions['iStartTime']);
            isset($conditions['iEndTime']) and $conditions['iEndTime'] = strtotime($conditions['iEndTime'] . ' +1 day');
            $conditions = ['K' => json_encode($conditions)];

            $response = $httpClient->post($statsConfig['path_' . $dataType], $conditions);
            $result = $response->toArray();

            if (!$result) {
                return json_encode(['total' => 0, 'rows' => [], 'error' => $response]);
            }
            if ($result['R'] != 200 || !$result['D']) return json_encode(['total' => 0, 'rows' => [], 'error' => $response]);
            $result = json_decode(Tool::unZipData($result['D'], $result['Z']), true);

        }
        return json_encode(['total' => count($result), 'rows' => $result]);
    }

    /**
     * 个人统计任务列表页面
     *
     * create by ck 20170629
     * modify by ck 20170630    增加权限及删除按钮
     */
    public function userStatsTaskAction()
    {
        $this->view->pick('stats/userStatsTask');
        Main::showNavPosition();
        UserPower::checkUserPower('Stats_User') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', true));
        Assets::easyUI('js/stats/userStatsTask.js');
        Assets::select2();
        $listButtonArr   = [];
        $listButtonArr[] = ['id'=>'bt_list_add', 'text'=>'新增查询', 'icon'=>'fa-plus'];
        if(UserPower::checkUserPower('Stats_User_Del')){
            $listButtonArr[] = ['id'=>'bt_list_del', 'text'=>'删除', 'icon'=>'fa-trash'];
        }
        $this->view->setVars([
            'List'      => Template::createList('List', 'stats/XHStats_TaskUser', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'schoolArr' => XhschoolInfo::getSchoolSupportArray()
        ]);
    }

    /**
     * 获取个人统计任务列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170629
     */
    public function getUserStatsTaskAction()
    {
        $parameters = [
            'conditions' => 'bDelete = 0',
            'order'      => 'iTaskId DESC'
        ];
        $data = Main::runModelPage('\\Admin\\Models\\stats\\XhstatsTaskuser', $parameters, $this->userTaskEnum);
        Main::runUserNameById($data['rows'], ['iStatsUserId' => 'sStatsUserName'], true);
        Main::runSchoolNameByIdStr($data['rows'], ['iSchoolId' => 'sSchoolName'], true);
        return $this->response->setJsonContent($data);
    }

    /**
     * 检查id下状态及已完成人数
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170630
     */
    public function checkUserStatsTaskAction()
    {
        $idArr = $this->request->getPost('ids', 'int');
        $data = XhstatsTaskuser::find([
            'columns'    => 'iTaskId,iStatus,iStatsNum,iCompleteNum',
            'conditions' => 'iTaskId IN ({idArr:array})',
            'bind'       => ['idArr' => $idArr]
        ])->toArray();
        return $this->response->setJsonContent($data);
    }

    /**
     * 删除任务
     *
     * create by ck 20170630
     */
    public function delUserStatsTaskAction()
    {
        if(!UserPower::checkUserPower('Stats_User_Del')){
            return $this->sendErrorResponse(403, '没有删除权限！');
        }
        $idArr = $this->request->getPost('ids', 'int');
        if(!$idArr){
            return $this->sendErrorResponse(400, 'id不能为空！');
        }
        $result = XhstatsTaskuser::find([
            'conditions' => 'iTaskId IN ({idArr:array})',
            'bind'       => ['idArr' => $idArr]
        ])->delete();
        if(!$result){
            return $this->sendErrorResponse(500, '删除失败！');
        }
        return $this->sendSuccessResponse('删除成功！');
    }

    /**
     * 个人使用情况页面
     *
     * create by ck 20170628
     */
    public function userStatsAction()
    {
        $this->view->pick('stats/userStats');
        UserPower::checkUserPower('Stats_User') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', true));
        Assets::easyUI('js/stats/userStats.js');
        $taskId   = $this->request->getQuery('taskId', 'int');
        $userType = $this->request->getQuery('userType', 'int');
        $taskId or die(Main::showMessageModal('缺少任务ID！'));
        in_array($userType, [1, 4]) or die(Main::showMessageModal('用户类型不正确！'));
        $this->view->setVars([
            'List'      => Template::createList('List', $userType == 1 ? 'stats/XHStats_Stud' : 'stats/XHStats_Tch', [
                'checkbox'      => false,
            ]),
        ]);
    }

    /**
     * 获取个人使用情况
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170628
     * modify by ck 20170629    去除学校等属性
     */
    public function getUserStatsAction()
    {
        $taskId = $this->request->getPost('taskId', 'int');
        if(!$taskId){
            return $this->sendErrorResponse(400, '缺少任务ID！');
        }
        $task = XhstatsTaskuser::findFirst($taskId);
        if(!$task){
            return $this->sendErrorResponse(400, '任务ID下无信息！');
        }
        $parameters = [
            'conditions' => 'bDelete = 0 AND iTaskId = ?0',
            'bind'       => [$taskId],
            'order'      => 'iSSId DESC'
        ];
        if($task->iUserType == 1){
            $data = Main::runModelPaginator('\\Admin\\Models\\stats\\XhstatsStud', $parameters, true);
            Main::runUserNameById($data['rows'], ['iStudId' => 'sStudName'], true);
            foreach($data['rows'] as $index => $row){
                $data['rows'][$index]['CA101006_Duration'] = Tool::secondToTime($row['CA101006_Duration']);
            }
        }
        else{
            $data = Main::runModelPaginator('\\Admin\\Models\\stats\\XhstatsTch', $parameters, true);
            Main::runUserNameById($data['rows'], ['iTchId' => 'sTchName'], true);
        }
        return $this->response->setJsonContent($data);
    }

    /**
     * 处理用户数据并统计数据写入数据库
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170628
     * modify by ck 20170629    添加任务表
     * modify by ck 20170630    状态区分，捕获异常
     */
    public function dealUserStatsAction()
    {
        if(!UserPower::checkUserPower('Stats_User')){
            return $this->sendErrorResponse(403, '没有查询权限！');
        }

        set_time_limit(0);
        ignore_user_abort(true);
        $schoolId = $this->request->getPost('iSchoolId', 'int');
        $userType = $this->request->getPost('iUserType', 'int');
        $textType = $this->request->getPost('textType', 'int');
        $content  = $this->request->getPost('content', 'string');
        $errorTag = false;

        //处理数据
        if(!$schoolId){
            return $this->sendErrorResponse(400, '学校Id不能为空！');
        }
        if(!$content){
            return $this->sendErrorResponse(400, '列表内容不能为空！');
        }
        $contentArr = explode(',', $content);
        switch($textType){
            case 1: {
                $users = XhsysUser::find([
                    'columns'    => 'iUserId',
                    'conditions' => "iUserId IN ({idArr:array}) AND bDelete = 0 AND iUserType = :userType: AND iSchoolId IN ({$schoolId},0,900090009)",
                    'bind'       => ['userType' => $userType, 'idArr' => $contentArr],
                    'bindType'   => ['userType' => Column::BIND_PARAM_INT, 'idArr' => Column::BIND_PARAM_INT]
                ]);
                break;
            }
            case 2: {
                $users = XhsysUser::find([
                    'columns'    => 'iUserId',
                    'conditions' => "sLogonName IN ({logonName:array}) AND bDelete = 0 AND iUserType = :userType: AND iSchoolId IN ({$schoolId},0,900090009)",
                    'bind'       => ['userType' => $userType, 'logonName' => $contentArr],
                    'bindType'   => ['userType' => Column::BIND_PARAM_INT, 'logonName' => Column::BIND_PARAM_STR]
                ]);
                break;
            }
            case 3: {
                $users = XhsysUser::find([
                    'columns'    => 'iUserId',
                    'conditions' => "sUserName IN ({userName:array}) AND bDelete = 0 AND iUserType = :userType: AND iSchoolId IN ({$schoolId},0,900090009)",
                    'bind'       => ['userType' => $userType, 'userName' => $contentArr],
                    'bindType'   => ['userType' => Column::BIND_PARAM_INT, 'userName' => Column::BIND_PARAM_STR]
                ]);
                break;
            }
            default: return $this->sendErrorResponse(400, '输入类型不正确！');
        }
        $users = $users->toArray();
        if(!$users){
            return $this->sendErrorResponse(400, '找不到有效用户！', $users);
        }
        $userIdArr = array_column($users, 'iUserId');

        //新建任务
        $task = new XhstatsTaskuser();
        $task->iSchoolId    = $schoolId;
        $task->iUserType    = $userType;
        $task->iStatsUserId = Main::getLoginUserInfo('userId');
        $task->iStatus      = 0;
        $task->iStatsNum    = count($userIdArr);
        $task->iCompleteNum = 0;
        $task->tStatsTime   = date('Y-m-d H:i:s');
        $task->mRemark      = $this->request->getPost('mRemark', 'string');
        $task->mInputInfo   = json_encode($this->request->getPost(), JSON_UNESCAPED_UNICODE);
        if(!$task->save()){
            return $this->sendErrorResponse(500, '任务保存失败！');
        }

        if($userType == 1){
            foreach($userIdArr as $userId){
                $studInfo = new XhstatsStud();
                $studInfo->iTaskId      = $task->iTaskId;
                $studInfo->iStudId      = $userId;
                $studInfo->tStatsTime   = date('Y-m-d H:i:s');
                try{
                    $statsInfo = $this->dealStudStats($schoolId, $userId);
                }
                catch(\Exception $e){
                    $errorTag = true;
                }
                $studInfo->assign($statsInfo);
                if($studInfo->save()){
                    $task->iCompleteNum++;
                    $task->save();
                }
            }
        }
        else if($userType == 4){
            foreach($userIdArr as $userId){
                $tchInfo = new XhstatsTch();
                $tchInfo->iTaskId       = $task->iTaskId;
                $tchInfo->iTchId        = $userId;
                $tchInfo->tStatsTime    = date('Y-m-d H:i:s');
                try{
                    $statsInfo = $this->dealTchStats($schoolId, $userId);
                }
                catch(\Exception $e){
                    $errorTag = true;
                }
                $tchInfo->assign($statsInfo);
                if($tchInfo->save()){
                    $task->iCompleteNum++;
                    $task->save();
                }
            }
        }
        if($task->iStatsNum == $task->iCompleteNum){
            $task->iStatus = 1;
            if($errorTag){
                $task->iStatus = 2;
            }
        }
        elseif($task->iStatsNum > $task->iCompleteNum){
            $task->iStatus = 3;
        }
        $task->save();
        return $this->sendSuccessResponse('success');
    }

    /**
     * 根据学校id，学生id获取该学生总信息
     *
     * @param $schoolId
     * @param $userId
     * @return array
     *
     * create by ck 20170628
     */
    private function dealStudStats($schoolId, $userId)
    {
        static $httpClient;
        $totalStats = [];
        $db = Main::getSchoolMainDB($schoolId, $dbName);

        //云作业做题量
        $coIdArr = $this->getStudCollId($db, $userId, 0);
        foreach($coIdArr as $coId){
            $dbCourseName = $dbName . '_course' . $coId;
            $result = $db->fetchOne("select count(an_id) as total from {$dbCourseName}.answer_student_homework_base left join {$dbCourseName}.homework_list_base on an_ho_id=ho_id where an_us_id = '{$userId}' and ho_parent_id = 0");//an_dates
            if($result['total']){
                @$totalStats['CA103001_Brush'] += $result['total'];
            }
        }

        //数刷做题量
        $coIdArr = $this->getStudCollId($db, $userId, 11);
        foreach($coIdArr as $coId){
            $dbCourseName = $dbName . '_course' . $coId;
            $result = $db->fetchOne("select count(uc_id) as total from {$dbCourseName}.st_upload_content where uc_us_id = '{$userId}' ");//uc_update
            if($result['total']){
                @$totalStats['CA101001_Brush'] += $result['total'];
            }
        }

        //科刷做题量
        $coIdArr = $this->getStudCollId($db, $userId, 13);
        foreach($coIdArr as $coId){
            $dbCourseName = $dbName . '_course' . $coId;
            $result = $db->fetchOne("select count(uc_id) as total from {$dbCourseName}.st_upload_content where uc_us_id = '{$userId}'");//uc_update
            if($result['total']){
                @$totalStats['CA101002_Brush'] += $result['total'];
            }
        }

        //英语做题量
        $coIdArr = $this->getStudCollId($db, $userId, 12);
        foreach($coIdArr as $coId){
            $dbCourseName = $dbName . '_course' . $coId;
            $result = $db->fetchOne("select count(sc_id) as total from {$dbCourseName}.yystw_studentchapter where sc_st_us_id = '{$userId}'");//sc_finishtime
            if($result['total']){
                @$totalStats['CA101003_Brush'] += $result['total'];
            }
        }

        //写汉字做题量
        $coIdArr = $this->getStudCollId($db, $userId, 5);
        foreach($coIdArr as $coId){
            $dbCourseName = $dbName . '_course' . $coId;
            $result = $db->fetchOne("select count(de_id) as total from {$dbCourseName}.ilc_detailsilc where de_ti_id in (select ti_id from {$dbCourseName}.ilc_titlesilc where ti_us_id = '{$userId}')");//de_time
            if($result['total']){
                @$totalStats['CA101007_Brush'] += $result['total'];
            }
        }

        //拼单词做题量
        $coIdArr = $this->getStudCollId($db, $userId, 6);
        foreach($coIdArr as $coId){
            $dbCourseName = $dbName . '_course' . $coId;
            $result = $db->fetchOne("select count(de_id) as total from {$dbCourseName}.ilc_detailsilc where de_ti_id in (select ti_id from {$dbCourseName}.ilc_titlesilc where ti_us_id = '{$userId}')");//de_time
            if($result['total']){
                @$totalStats['CA101008_Brush'] += $result['total'];
            }
        }

        //美文阅读数
        $coIdArr = $this->getStudCollId($db, $userId, 10);
        foreach($coIdArr as $coId){
            $dbCourseName = $dbName . '_course' . $coId;
            $result = $db->fetchOne("select count(*) as total from {$dbCourseName}.essay_read_detail where rd_us_id = '{$userId}'");//rd_time
            if($result['total']){
                @$totalStats['CA105002_Practice'] += $result['total'];
            }
        }

        //听力时长
        $coIdArr = $this->getStudCollId($db, $userId, 4);
        foreach($coIdArr as $coId){
            $dbCourseName = $dbName . '_course' . $coId;
            $result = $db->fetchOne("select sum(de_spetime) as total from {$dbCourseName}.hb_details where de_us_id = '{$userId}'");//de_starttime
            if($result['total']){
                @$totalStats['CA101006_Duration'] += $result['total'];
            }
        }

        //古文做题量（接口）
        if(!$httpClient){
            $gwConfig   = Main::getConfigByName('stats_CA101004');
            if(!$gwConfig['url']){
                goto end;
            }
            $httpClient = new HttpClient($gwConfig['url']);
        }
        $response = $httpClient->post('/statistics/getStuRequestInfo', ['K' => json_encode(['iStuId' => $userId]), 'Z' => 0]);
        if(!$response->isSuccess()){
            Main::createCommitLog('stats', 'userStats', 'httpErr', $response, $userId, '古文http请求失败');
        }
        $body     = $response->toArray();
        if(isset($body['D']) && json_decode($body['D'])){
            $result = json_decode($body['D'], true);
            if($result['stuWorkCount']){
                @$totalStats['CA101004_Brush'] += $result['stuWorkCount'];
            }
        }

        end:
        return $totalStats;
    }

    /**
     * 根据学校id，教师id获取该教师总信息
     *
     * @param $schoolId
     * @param $userId
     * @return array
     *
     * create by ck 20170628
     */
    private function dealTchStats($schoolId, $userId)
    {
        $totalStats = [];
        $db = Main::getSchoolMainDB($schoolId, $dbName);

        //获取教师云作业co_id数组
        $coIdArr = $db->fetchAll("select  te_co_id from teacher_list where te_us_id = '{$userId}' and te_co_id in (select co_id from course_list where co_coach_flag='0')");
        $coIdArr or $coIdArr = [];
        $coIdArr = array_column($coIdArr, 'te_co_id');
        foreach($coIdArr as $coId){
            $dbCourseName = $dbName . '_course' . $coId;
            $leIdSql = "select le_id from {$dbCourseName}.lesson_course where le_us_id = '{$userId}' and le_tmpflag = 0";//le_dates
            //获取布置次数
            $result = $db->fetchOne("select count(le_id) as total from {$dbCourseName}.lesson_course where le_us_id = '{$userId}' and le_tmpflag = 0");//le_dates
            if($result['total']){
                @$totalStats['iFixNum'] += $result['total'];
            }
            //获取布置题量
            $result = $db->fetchOne("select count(lh_id) as total from {$dbCourseName}.lesson_homework_list where lh_ho_parent_id=0 and lh_le_id in ({$leIdSql})");
            if($result['total']){
                @$totalStats['iTopicNum'] += $result['total'];
            }
            //获取分层布置次数（组）
            $result = $db->fetchOne("select count(distinct(ob_le_id)) as total from {$dbCourseName}.object_student_homework where ob_flag=1 and ob_zb_id > 0 and ob_le_id in ({$leIdSql})");
            if($result['total']){
                @$totalStats['iFixGroupNum'] += $result['total'];
            }
            //获取错题卷组布置次数
            $result = $db->fetchOne("select count(le_id) as total from {$dbCourseName}.lesson_course where le_us_id = '{$userId}' and le_tmpflag = 0 and le_wrong_flag = 1");//le_dates
            if($result['total']){
                @$totalStats['iFixWrongNum'] += $result['total'];
            }
            //获取布置错题量
            $result = $db->fetchOne("select count(lh_id) as total from {$dbCourseName}.lesson_homework_list where lh_ho_parent_id=0 and lh_le_id in ({$leIdSql} and le_wrong_flag = 1)");
            if($result['total']){
                @$totalStats['iTopicWrongNum'] += $result['total'];
            }
        }
        //获取教师关联题库id
        $trIdArr = $db->fetchAll("select tk_tr_id from tk_power where tk_us_id = '{$userId}'");
        $trIdArr or $trIdArr = [];
        $trIdArr = array_column($trIdArr, 'tk_tr_id');
        foreach($trIdArr as $trId) {
            $dbExamName = $dbName . '_exam' . $trId;
            $result = $db->fetchOne("select count(li_id) as total from {$dbExamName}.list_courseware where li_us_id = '{$userId}'");//li_datetimes
            if($result['total']){
                @$totalStats['iCoursewareNum'] += $result['total'];
            }
        }
        return $totalStats;
    }

    /**
     * 根据学生id，老应用编号获取学生所在co_id
     *
     * @param Mysql $db
     * @param $studId
     * @param $oldAppCode
     * @return array
     *
     * create by ck 20170628
     */
    private function getStudCollId(Mysql $db, $studId, $oldAppCode)
    {
        $coIdArr = $db->fetchAll("select st_co_id from students_list where st_us_id = '{$studId}' and st_co_id in (select co_id from course_list where co_coach_flag='{$oldAppCode}')");
        if(!$coIdArr) return [];
        $coIdArr = array_column($coIdArr, 'st_co_id');
        return $coIdArr;
    }

}

